I’ll ask you for some help with a really really simple program which implements a search planning algorithm. Well, the problem I got is a little weird for me: after allocating memory for a simple array of characters declared locally in a function, I work over this array, it has all the expected behaviors and everything goes ok, but when I call the free() function to this array before the function ends, the program stops and abort. If someone with some experience about this problem (or not…) could help me, i’d be really thankful. Well, here follows some lines of a “simulated” code to show what I’m talking about (it’s not exactly what’s written, but the :
char* v_AllTheWorld
char* v_ReadALineOfTheWorld;
v_AllTheWorld = malloc(COLUMNS * LINES * sizeof(char)); /*LINES and COLUMNS are defined constants*/
if(v_AllTheWorld == NULL)
{
fprintf(stderr, "..."); //etc, etc.
exit(1);
}
v_ReadALineOfTheWorld = malloc(COLUMNS * sizeof(char)); /*the "sizeof(char)" looks useless, but there's no point in talking about that here, i guess.*/
if(v_ReadALineOfTheWorld == NULL)
{
fprintf(stderr, "..."); //etc, etc.
exit(1);
}
while(/*some_condition (number of lines to be read)*/)
{
//read data string from stream and stores in v_ReadALineOfTheWorld (fscanf);
//appends the read data to v_AllTheWorld (strncat);
}
free(v_ReadALineOfTheWorld);
/*The program is stopping right after this call in the debug.*/
return v_AllTheWorld;
I didn’t put the head of the function, the declaration of it, and I didn’t represent the stream or how the data is manipulated in details, but no other calls of “malloc” or “free” are made and all the code that is written is executed unconditionally (out of any “if” or similar). Course, the last bahavior doesn’t include the allocation tests, but you got what I’m saying.
So, well, I hope I did it right asking this way, I hope I detailed the problem the right way and I hope you may help me.
Oh, I almost forgot that: as you probably noticed, the program is in C.
This could happen if you are writing outside the bounds of
v_ReadALineOfTheWorld. Somemalloclibraries store info about themallocd region in a wrapper around the region, and if you corrupt that infofreecould crash.