Search code examples
cstringassertundefined-behaviorstring-literals

How to check if a string passed as argument is a modifiable string


The question is pretty much in the title.

The code

void modify_str(char* str){
    
    if(strlen(str) > 5) {
       str[5] = 'x';
    }
}

Will invoke undefined behavior if a string literal is passed as argument, i.e.:

modify_str("some text");

Or

char *str = "some text";
modify_str(str);

Is there any way to assert at runtime that a string passed as argument is not a string literal, but a modifiable string?


Solution

  • String literals in C have type char [] so there's no standard-compliant way of doing this.

    Some compilers however have flags which can change the type of string literals to const char [] so that you would get a warning for code like this.

    If you're using gcc, add the -Wwrite-strings flag to make string literals have type const char []. Then you'll get a warning like this:

    x1.c: In function ‘main’:
    x1.c:14:16: warning: passing argument 1 of ‘modify_str’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
         modify_str("some text");
                    ^~~~~~~~~~~
    x1.c:4:23: note: expected ‘char *’ but argument is of type ‘const char *’
     void modify_str(char* str){
                     ~~~~~~^~~