Pergunta

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?

Foi útil?

Solução

free() function only marks a memory block as "free". That means, that at any moment, it cam be used by other function. It does not clean up the memory as it supposed to be handled by the program that will get this memory block next time.

What you actually done, is undefined behavior.

Outras dicas

When you free a memory, you just loose control over it. You release the memory for any other use. It does not get overwritten or occupied by other function or variable immediately. But it can be used by other function or variable at any unknown time. Until then, you will be able to access the memory. But as one cannot be sure about the time when it will be used by others, the behaviour is undefined.

  • In case you want to make sure that the memory become inaccessible using the same variable, set them to NULL after freeing.

free marks the memory as being free for reuse. After free you are responsible for not attempting to use the memory again. It is possible that the memory is still intact after freeing, hence your groupName printing fine. However it could also have been reallocated, hence the segfault in imageName

When freeing memory, the pointers still point to the memory that was allocated, and its contents may (or may not) be overwritten by other data. This is why it seems to work some times. Undefined behavior tends to be, well, undefined.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top