Can `const char *` cause problems?
No. By its very nature, one free()
needs the freedom to write into a given memory, to do "accounting". This is why he determined to take the pointer not const
.
As others have pointed out, this does not mean that it cannot work; C can drop the const
-ness of the pointer and let the function behave as if it were called without const
. The compiler will warn you when this happens, so I believe this is "causing problems".
a source to share
If the pointer is assigned yes. You will get a warning, but you have it when you highlighted it.
I use it a lot const char *
in my frameworks when I want to make sure no one else writes to them between distribution and release. It often happens that you dynamically create a string that is immutable for life, and if you call it with a function with side effects ( strtok
), you might run into problems. By declaring it const
, you can at least get a warning in this case.
const char *msg;
asprintf((char *)&msg, "whatever" ...);
...
strtok(msg, ","); // Will generate a warning
...
free((char*)msg);
a source to share