Should I free char* initialized using string-literals?

You shall never free() memory that you did not malloc()ed.

The way the compiler implements string-literals is not your business: it’s an implementation detail. You can free() a pointer to memory that you allocated using malloc(), and only those, or you are risking the life of your system.

Ideally, malloc() calls and free() calls should appear on the same “design level” (inside the same implementation file for the same module for example), and they should match perfectly: one free() for each malloc(). but that’s not always possible.

(Note that some library allocates blocks of memory, returns pointers to those blocks, and instructs you to free them. in this case, you are allowed to free those pointers, but that is a bad design practice from the people who created the library.)

Leave a Comment