simple char array access causes crash- why??

This very simple function is crashing and I cant see why- every time I try to change the value of str[i] I get an access violation, and I don't understand why this is happening- anybody know?

void ChangeToSpace (char* str)
{
size_t n = strlen(str) ;
for (size_t i = 0; i < n; i++)
{
str[i] = 0x20; // crash :(
}
}
[383 byte] By [azimuth_rising] at [2007-11-20 11:42:03]
# 1 Re: simple char array access causes crash- why??
This very simple function is crashing and I cant see why- every time I try to change the value of str[i] I get an access violation, and I don't understand why this is happening- anybody know?How did you call this function? What parameter did you pass?

This will *not* work:

#include <cstring>

void ChangeToSpace (char* str)
{
size_t n = strlen(str) ;
for (size_t i = 0; i < n; i++)
{
str[i] = 0x20;
}
}

int main()
{
ChangeToSpace("abc123"); // string literal -- cannot be changed
}

String literals cannot be changed. If you do that, the behaviour is undefined. The program will more than likely crash.

Regards,

Paul McKenzie
Paul McKenzie at 2007-11-10 22:24:29 >
# 2 Re: simple char array access causes crash- why??
It isn't the function call itself, even if I just try to change a string in main, like

main()
{
char* str = "Hello" ;
str[0] = 32;
}

I get the same crash. Are you not allowed to change the entries in a char array? I've never run into this problem before, it seems very strange to me.
azimuth_rising at 2007-11-10 22:25:30 >
# 3 Re: simple char array access causes crash- why??
Your program (same as Pauls sample), has a pointer to a fixed literal. Either copy the literal into a buffer, or even better stop using 30 year old techniques, and use proper STL strings.
TheCPUWizard at 2007-11-10 22:26:33 >
# 4 Re: simple char array access causes crash- why??
like Paul McKenzie said, a char* string litteral cannot be changed. However this will work if you use a char array instead.

char str[] = "Hello";
str[0] = 32;
bovinedragon at 2007-11-10 22:27:38 >
# 5 Re: simple char array access causes crash- why??
Are you not allowed to change the entries in a char array?Yes, you can change the entries in a char array. The problem is that what you declared is not an array -- it is a string literal.

char *p = "abc123"; // string literal, cannot be changed
char p2[] = "abc123"; // an array of char, which can be changed.

Regards,

Paul McKenzie
Paul McKenzie at 2007-11-10 22:28:32 >
# 6 Re: simple char array access causes crash- why??
Yes that worked.. thanks guys!
azimuth_rising at 2007-11-10 22:29:30 >