Friday, February 11, 2011

String Literals

What is wrong with the following code?


#include <cstdio>
#include <cstdlib>
#include <iostream>


using namespace std;


int main(int argc, char** argv)
{
    char *str = "hello world";


str[0] = 'H';


    return 0;
}


Consider:

char str[256];
strcpy(str, "hello world");


instead of:

char *str = "hello world";

Why?
The compiler puts the string literal ("hello world") into the read only address space of the program and thus is immutable during runtime. Which explains why there is a segmentation fault/exception thrown when one tries to write to str.

More Info: String Literals - Where do they go?

No comments:

Post a Comment