这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值

What is this pointer and memory code printing? I don't know if it's printing garbage or how to print the value that I need

本文关键字:打印 何打印 内存 指针 代码 是什么 我不知道      更新时间:2023-10-16

这是我从一个更大的代码中提取的一段代码。我需要弄清楚我打印的内容是否是垃圾,以及如何更改它以打印我需要的值。我需要它来打印int id的值,而不是它打印的任何值。在这次运行中,输出是10813776,当然,每当我更改一些代码或重新启动DevC++时,它就会发生变化。

代码为:

#include <iostream>
#include <memory> //Memory allocation (malloc)
using namespace std;
int main(){
int id = 0;
int nMemory = 0;
int * pMemory;
pMemory = (int *) malloc(20 * sizeof(int));

while(id < 20){
if (pMemory != NULL){
cout << "Numbers in memory: " << endl;
pMemory = new int[id];
nMemory = *pMemory;
cout << nMemory << endl;
}
id++;
}
delete pMemory;

return 0;
}
pMemory = new int[id];
nMemory = *pMemory;

第一行用一个未初始化的新数组替换malloc初始化的数组,然后尝试从该新数组的第一个插槽中读取。您不应该直接分配给pMemory;可能到pMemory[someIndex]而不是到pMemory本身。

您是否正在尝试读取pMemory数组并将其分配给nMemory?如果是,请将上面的行更改为:

nMemory = pMemory[id];

你的整个循环应该看起来更像这样:

if (pMemory != NULL) {
cout << "Numbers in memory: " << endl;
while(id < 20) {
nMemory = pMemory[id];
cout << nMemory << endl;
id++;
}
}

或者,使用更惯用的for循环:

if (pMemory != NULL) {
cout << "Numbers in memory: " << endl;
for (int i = 0; i < 20; i++) {
cout << pMemory[i] << endl;
}
}

(你还必须在这个循环上方的某个地方初始化数组。我想你在实际代码中会这样做,但如果不是这样:你发布的代码分配了一个带有malloc()的数组,但没有将项设置为有用的值。在你尝试读取和打印它们之前,请确保将它们设置为有意义的值。(

此代码正在泄漏您使用malloc()new[]分配的内存块。

malloc()是一个内存块,并将其地址分配给pMemory,然后将pMemory更改为指向与new[]分配的不同内存地址。所以你失去了free()的能力——malloc()的内存(你甚至没有试图调用free()(。

而且,此代码没有正确释放使用new[]分配的内存。用new[]分配的内存必须用delete[]释放,而不是用delete释放。更糟糕的是,您在一个循环中调用new[]20次,但在循环之后只调用delete一次。因此,您泄漏了19个new[]ed内存块,并且有未定义的行为释放了1个块。

现在,为了回答您的实际问题,代码正在打印垃圾,因为您使用new[]分配的内存是未初始化的,所以您试图从该内存打印的数据包含不确定的值。