关于自由函数和内存分配的问题 ( C )



我试图理解 C 中的指针和内存分配。所以我有这些 C 代码行:

int *a=0; // a pointer which points to 0
a = (int*)malloc(5*sizeof(int));  // now the pointers a points to the adress of our allocated memory, right ?
if (a == 0) 
{
fprintf(stderr, "Errorn");
exit(EXIT_FAILURE);
}
printf("The value of a is %pn", a); // this is the adress of our allocated memory
a=readArray(5); // a function which reads and array // What happens here? I read an array in that memory which I allocated, right ?
printf("Now the value of a is: %pn", a); // Now the adress is the adress of first array element, right?
if (a != 0)
{
free(a);
a=0;
}

该程序的输出是:

The value of a is 0x7ff780c03160
Now the value of a is: 0x7ff780c03180

现在我需要选择一个关于自由函数调用的答案。

1. Deallocates the both allocated memory zones.
2. Deallocates the memory starting at adress 0x7ff780c03180 and fill that zone with zeros.
3. Deallocates the memory starting at adress 0x7ff780c03180
4. Deallocates the memory starting at adress 0x7ff780c03160

从我读到的关于自由函数的内容来看,它会释放整个内存,建议用 0 初始化指针。所以我认为答案是第一个变体,1。我说的对吗?

readArray

无法访问a(a不是全局变量,也不会传递给readArray),这意味着readArray必须分配一个新数组并返回它。然后这个数组被分配给a,在这个过程中丢失了对原始malloc数组的引用。

free调用应用于从0x7ff780c03180开始的新数组,得出正确答案 #3。

不,free()只会释放传递给它的指针给出的内存块。因此,这将从地址0x7ff780c03180开始释放内存,地址 0x7ff780c03160 处的内存将被泄漏。

不,free不会释放超过传递给它的分配指针。列表中的正确答案是 3。free将释放a在该时间点指向的内存,仅此而已。它不会用零或其他任何东西填充该内存区域。

此外,当您readArray(5)时,您可以创建分配新内存并保留之前分配的旧内存。所以你正在一步一步地做什么:

  1. 使用malloc分配了一些内存(我们称之为X),并将其地址存储在变量a中。
  2. 调用readArray,它将分配一些其他内存(我们称之为Y)并将其地址存储在a中。
  3. 释放存储在a中的内存,这是Y分配的内存块。

现在标记为X的内存将悬而未决,这意味着您没有任何引用,也无法解除分配它。它只是分配的内存,无法再访问,因为您丢失了指向它的指针。

答案是3.

使用行a=readArray(5);您将丢失前一个指针(示例中为 160)。您无法再free此内存,因此存在内存泄漏。==>14不可能是正确答案。

free不会用零填充内存,a=0也只将指针变量设置为0,但对内存 ==>2不执行任何操作不是正确答案。

最新更新