cgccstring-literalsfunction-parameter

String in function parameter


int main()
{
        char *x = "HelloWorld";
        char y[] = "HelloWorld";

        x[0] = 'Z';
        //y[0] = 'M';

        return 0;
}

In the above program, HelloWorld will be in read-only section(i.e string table). x will be pointing to that read-only section, so trying to modify that values will be undefined behavior.

But y will be allocated in stack and HelloWorld will be copied to that memory. so modifying y will works fine. String literals: pointer vs. char array

Here is my Question:

In the following program, both char *arr and char arr[] causes segmentation fault if the content is modified.

void function(char arr[])
//void function(char *arr)
{
   arr[0] = 'X';
}        
int main()
{
   function("MyString");    
   return 0;
}
  1. How it differs in the function parameter context?
  2. No memory will be allocated for function parameters??

Please share your knowledge.


Solution

  • Inside the function parameter list, char arr[] is absolutely equivalent to char *arr, so the pair of definitions and the pair of declarations are equivalent.

    void function(char arr[]) { ... }
    void function(char *arr)  { ... }
    
    void function(char arr[]);
    void function(char *arr);
    

    The issue is the calling context. You provided a string literal to the function; string literals may not be modified; your function attempted to modify the string literal it was given; your program invoked undefined behaviour and crashed. All completely kosher.

    Treat string literals as if they were static const char literal[] = "string literal"; and do not attempt to modify them.