0

I have a struct containing a bunch of char pointers whose values are used throughout the program's lifetime. Most are overwritten every iteration.

Should these values be freed at any point besides program exit? Should the value in the char pointer be freed before overwriting it with strdup("new value")?

Kagemand Andersen
  • 1,470
  • 2
  • 16
  • 30
  • 2
    For every `malloc` or `realloc` or `calloc`, you should call `free`. The `strdup` function calls `malloc` (or `calloc`). – Some programmer dude Mar 13 '18 at 08:41
  • Yes it should, not doing so is a memory leak and depending on the number of allocations your program does, that could quickly become a very bad thing. – Iharob Al Asimi Mar 13 '18 at 08:43
  • Some caution is required with `realloc()`; if you reallocate something allocated with `malloc()` or `calloc()`, you should not free the 'before' pointer (`malloc()` or `calloc()`) any more, only the after pointer (`realloc()`). If you reallocate an already reallocated pointer, you should only free the last such pointer returned. OTOH, if you used `realloc()` to free some memory (new size 0), you probably don't need to free that — unless `realloc()` did not return a NULL pointer for the zero-size reallocation. – Jonathan Leffler Mar 13 '18 at 08:43
  • @Someprogrammerdude so even when overwriting the value, you should free the pointer before overwriting it? Just want to make sure. – Kagemand Andersen Mar 13 '18 at 08:45
  • 1
    If the memory was allocated, you should free it before overwriting the (only) pointer to that memory. Not doing so is a memory leak. If the memory remains in use until exit, it isn't crucial that it is freed before exit. OTOH, being able to free it all before exit reassures that you can handle the memory cleanly. – Jonathan Leffler Mar 13 '18 at 08:50
  • Just to add, you don't free the values. You deallocate the memory allocated. Even after free-ing, the values may remain at the meomory locations. – awakened Mar 13 '18 at 09:00

2 Answers2

2

@some-programmer-dude is right, there will be memory leak without free if your program works like a server.

BTW, all memory will be released after the program exited no matter whether you call free() or not.

Larry.He
  • 604
  • 5
  • 16
  • 1
    Regarding the freeing when program exits, that is very platform and OS dependent. The big common operating systems do that, but it's not a general rule or requirement. – Some programmer dude Mar 13 '18 at 09:08
0

You already got the answer. I'm just providing more information and reference to it.

Man page of POSIX standard strdup.

Here we go,

   The strdup() function returns a pointer to a new string which is a
   duplicate of the string s.  Memory for the new string is obtained
   with malloc(3), and can be freed with free(3).
danglingpointer
  • 4,708
  • 3
  • 24
  • 42