In general you only have to free memory that has been reserved for you dynamically. That means if you have a statement like this:
int *my_int_pointer;
my_int_pointer = malloc(sizeof(int));
than you need to free the memory that was allocated (reserved) by malloc.
if you are unsure where to free it than just free it at the end of the program, by using free;
free(my_int_pointer);
In your file it looks like there will be memory allocated whenever there is a new line in the file you read (in the while(done==0)
loop). so everytime after the if
in the this loop you have to free the memory that was used by the variable.
Furthermore you need to free the memory that was allocated by for the readline variable. But as it was pointed out before you may have a memory leak there.
Hope this helps.
edit: Okay - I was already wondering about the csestrcpy
function. Lets have a look at this function:
char* csestrcpy2(char* src){
int i = 0;
char *dest;
char t;
dest = (char*) malloc(MAX_LINE); /*<<- This allocates memory that has to be freed*/
while( src[i] != '\0'){
dest[i] = src[i];
i++;
}
dest[i] = '\0';
//printf("length:%i\n",i);
free(dest); /* This frees the memory, but you return a pointer */
return dest; /* to this memory. this is invalid. */
}
What you could however free is the src pointer in that function. but remember: the pointer cannot hold information after the underlying memory is freed! It just points to a place in memory where it should not write or read anymore.
Furthermore the function copys the string as long as there is no '\0'. What happens if there is no terminator? The function keeps on copying from some memory adresses where it should not!
you should not use that function ;)
Best Answer
That's undefined behavior - never try it.
Let's see what happens when you try to
free()
an automatic variable. The heap manager will have to deduce how to take ownership of the memory block. To do so it will either have to use some separate structure that lists all allocated blocks and that is very slow an rarely used or hope that the necessary data is located near the beginning of the block.The latter is used quite often and here's how i is supposed to work. When you call malloc() the heap manager allocates a slightly bigger block, stores service data at the beginning and returns an offset pointer. Smth like:
then
free()
will try to access that data by offsetting the passed pointer but if the pointer is to an automatic variable whatever data will be located where it expects to find service data. Hence undefined behavior. Many times service data is modified byfree()
for heap manager to take ownership of the block - so if the pointer passed is to an automatic variable some unrelated memory will be modified and read from.Implementations may vary but you should never make any specific assumptions. Only call
free()
on addresses returned bymalloc()
family functions.