Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

string

literals

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;
}
like image 519
SiegeX Avatar asked Feb 23 '10 23:02

SiegeX


2 Answers

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

like image 160
Anon. Avatar answered Sep 18 '22 08:09

Anon.


Your chomp should ideally create a new string and return it. There is no way to determine if you were passed a string literal or not. In fact, I'd suggest using the following signature for chomp:

char *chomp(const char *s); /* do not modify input parameters */

Or, you could create two different functions and document them for the clients: use chomp for non-literals and chompl for literal strings.

like image 29
dirkgently Avatar answered Sep 20 '22 08:09

dirkgently