1

I was writing a code to check if two functions I wrote to allocate and deallocate memory worked. The two functions were essentially

int createBaseName(char ***imageName, char **groupName, char *name)
{
    *imageName = calloc(BASELINEC, sizeof(char *)); //This is a 2D array (array of str)
    *groupName = calloc(MINILINE, sizeof(char)); // This is a 1D array (just an str)

    sprintf(*groupName, "%s_BGr.fbi", name);
    for(bb = 0; bb < BASELINEC; bb++) {
       (*imageName)[bb]  = (char *)calloc(MINILINE, sizeof(char));
        if (bb < 9)
           sprintf((*imageName)[bb], "%s_BIm_00%d.fbi", name, bb+1);
        else if (bb < 99) 
           sprintf((*imageName)[bb], "%s_BIm_0%d.fbi", name, bb+1);
        else
           sprintf((*imageName)[bb], "%s_BIm_%d.fbi", name, bb+1);
   }
   return 0;
}

and

int freeBaseName(char **imageName, char *groupName)
{
   int  bb;

   for(bb = 0; bb < BASELINEC; bb++)
      free(imageName[bb]);

   free(imageName);
   free(groupName);

   return 0;
}

In the program I wrote to check these two functions, I accidentally called createBaseName and freeBaseName one after the other, and then I was attempting to print out imageName and groupName. This resulted in groupName printing just fine, and about a 120 of 400 names of imageName printing fine before it segfaulted.

QUESTION: Why wasn't the free-ing of the memory working? Or does it take time to free the memory?

4

4 回答 4

2

free()函数仅将内存块标记为“空闲”。这意味着,在任何时候,它都可以被其他功能使用。它不会清理内存,因为它应该由下次获取此内存块的程序处理。

您实际所做的是未定义的行为

于 2013-04-23T08:48:29.523 回答
2

当你free有记忆时,你只是失去了对它的控制。您释放内存用于任何其他用途。它不会立即被其他函数或变量覆盖或占用。但它可以在任何未知时间被其他函数或变量使用。在此之前,您将能够访问内存。但是由于无法确定其他人何时使用它,因此行为undefined

  • 如果您想确保使用相同的变量无法访问内存,请将它们设置为NULLafter freeing。
于 2013-04-23T09:20:42.380 回答
1

free将内存标记为可重用。在free您有责任不再尝试使用内存之后。释放后内存可能仍然完好无损,因此您的groupName打印正常。然而,它也可能被重新分配,因此在imageName

于 2013-04-23T08:48:47.623 回答
1

释放内存时,指针仍然指向已分配的内存,其内容可能(也可能不会)被其他数据覆盖。这就是为什么它有时会起作用的原因。未定义的行为往往是未定义的。

于 2013-04-23T08:51:09.460 回答