How to detect the passing of a string literal to a function in C?

c, literals, string

Solution

Is there a defined way in C99 to detect wether or not my function was passed a string literal so that I can return without attempting to NUL it out?

You shouldn't.

Your API shouldn't attempt to fudge things for the caller, only to have it break later on. If the caller breaks the rules, they should find out then and there.

If the caller passes a non-mutable string to a function that expects a mutable one, it should segfault. Anything else is bad design.

(Addendum: The best design, of course, would be to return a copy of the string that the caller is responsible for freeing.)

Problem

I am trying to implement an eqivilent version of perl's `chomp()` function in C and I have come across a corner case where a string literal passed as the argument will cause a segmentation fault (rightfully so). Example `chomp("some literal string\n");` Is there a defined way in C99 to detect wether or not my function was passed a string literal so that I can `return` without attempting to NUL it out? ``` char* chomp(char *s) { char *temp = s; if (s && *s) { s += strlen(s) - 1; if (*s == '\n') { *s = '\0'; } } return temp; } ```

Original source