Take the 2-minute tour ×

Possible Duplicate:
Why does this code snippet give segmentation fault

Sorry for the title maybe isn't good :) isn't allowed to write problem in title and it must contain 15 chars :( i have a little problem :(

char * Test(char * test){
    cout << test << endl; // this works fine :)

    int i = 0;
    while(*(test+i) != 0){
        *(test+i) += 128; // this doesn't work :(
    return test;

int main()
    char * testMain = "String Test";
    cout << Test(testMain) << endl;

    return 0;

I get an windows error !!!!! I don't know why !!!!!! I can write the string but i can't change it :(

share|improve this question

marked as duplicate by Jerry Coffin, leemes, billz, StilesCrisis, sashoalm Feb 2 '13 at 8:54


Mind posting the error you get? Also calm down, less exclamation marks are better for everyone ;) –  nemo Feb 2 '13 at 3:36

4 Answers 4

up vote 4 down vote accepted

All string literals are of type const char*, this means that trying to change the data in the string results in undefined behavior.

Windows is stopping you from changing memory that's supposed to be read only. I bet your compiler is warning you of this as well!

Try declaring your string in main like this instead:

char testMain[] = "String test"

This will create an array long enough to hold the "String test" and copy that data into it.

share|improve this answer
yeah it warning me :) but how do i fix it?? :) –  La VloZ Feb 2 '13 at 3:37
@LaVloZ: You cannot modify the literal, but you can copy it and then modify the copy, for example as suggested in this answer. –  David Rodríguez - dribeas Feb 2 '13 at 3:38
@LaVloZ I think I was adding that as you were commenting. Hope it helps. –  Collin Feb 2 '13 at 3:39
@Collin yes hihihi :P –  La VloZ Feb 2 '13 at 3:41

Inside function Test you are editing a constant string literal.

You can instead try to declare it like so:

char  testMain[] = "String Test";

or make a copy of it inside the function

share|improve this answer
Thank u so much :) –  La VloZ Feb 2 '13 at 3:42

Quoted strings are stored in memory that can't be changed or you will crash. Make a copy of the string into a char array first.

share|improve this answer
Thank u so much :) –  La VloZ Feb 2 '13 at 3:40
char * testMain = "String Test";

This is a deprecated feature in the language. String literals are arrays of constant characters. The compiler should have complained in that line of code. Given that it compiled you are obtaining a pointer to non-const that really refer to a constant character, effectively performing a const_cast. Using that pointer to modify the constant object is undefined behavior.

share|improve this answer
