Search code examples
c++stringvisual-studio-2010pointersstring-literals

Unhandled exception at C++


I receive this error

Unhandled exception at 0x00091e11 in JobTest.exe: 0xC0000005: Access violation writing location 0x0009573c.

on first line of this function

void myFunction(char str[]) {

    str[0] = 'C';// here is a problem
    printf(str);
}

myFunction("Hello World");

in visual studio 2010. Is it compiler specific or i am doing really bad job. i also tried by changing function signature char *str.


Solution

  • String literals are non-modifiable. You are trying to modify a string literal in function myFunction.
    String literals might be shared and could be stored in read-only memory (as @Duplicator said in his comment). Any attempt to modify a string literal invokes undefined behavior.

    As @MooseBoys suggested, You can fix it by changing it to:

    char msg[] = "Hello World"; 
    myFunction(msg);