When should I use free() in C?

烂漫一生 提交于 2019-12-03 07:13:00
Florian

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 ;)

There needs to be a call to free() for each successful call to malloc().

That doesn't necessarily mean that you need to have equal numbers of malloc() and free() calls in your code; it means that for every malloc() call that's executed when your program runs, you should call free(), passing it the pointer value you got from malloc(). malloc() allocates memory; free() tells the system that you're done with the allocated memory.

(You can almost certainly get away with not free()ing allocated memory when your program terminates, since it will be reclaimed by the operating system, but just as a matter of style and good practice you should still match malloc()s with free()s.)

I'm ignoring calloc() and realloc() calls.

Dayal rai

Dynamic memory allocation (malloc) allocates a memory block of requested size, and returns a pointer to the start of this block.Since we have taken this block from memory so its a good practice to return this back to memory after completion of task.

Now as answer of your question , To be always on safe side you can call free function before making return.

main{
    int *i;
    ..
    ..
    i=(int *)malloc(sizeof(int));
    ...//so something with i
    ..
    free(i);
    return 0;
}

As a general rule, for every malloc there should be a corresponding free. You cannot however free something twice (as you have noticed by now). I don't see any calls to free in your code, so it's impossible to say where your problem lies, but I noticed right away that you malloc some memory and assign it to readline inside of a loop, yet you don't call free on readline at the end of the loop, so you are leaking memory there.

Think of malloc and free as "begin" and "end". ANY time you call malloc, do what you need to and once you're done, always call free. Make sure to only free it once, double-free is a runtime error.

If you somehow lose the value returned by malloc (yes, this is what's happening with your code), then you have a memory leak (and the gates of hell open up, yada yada).

To re-iterate: free whatever malloc returns (except null).

This line:

strings_array[count_number_of_lines]=(char*)malloc(strlen(incoming_string+1));

is being overriden by the line next to it, so it can be removed.

You should also add free(readline) after count++ in the last loop to free the memory created by malloc.

        i++;
        j++;
        /// free here
        free(readline);
    }
    count++;

}
printf("current word count: %i", word_count);

//free here as well
for(int k = 0; k < count_number_of_lines; k++)
{
    free(strings_array[count_number_of_lines]);
}

return 0;
}

This should work.

In general - any memory allocated dynamically - using calloc/malloc/realloc needs to be freed using free() before the pointer goes out of scope.

If you allocate memory using 'new' then you need to free it using 'delete'.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!