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?