-
February 14th, 2009, 10:41 PM
#1
Why does this code crash?
Hi,
The following two lines of code crashes, can anyone let me know why?
char *s = "This is my String";
s[3] = 'a';
I do expect the result is: Thia is my String. But it crashes.
Regards,
Kevin
-
February 14th, 2009, 11:01 PM
#2
Re: Why does this code crash?
Originally Posted by silentray
Hi,
The following two lines of code crashes, can anyone let me know why?
The variable s is a string literal. It is undefined behaviour to attempt to modify a string literal.
I do expect the result is: Thia is my String. But it crashes.
On another compiler, it may give you those results. On some other compiler it crashes. On another compiler, it could reboot your computer, or blow up a space ship.
That's what is meant by undefined behaviour -- anything can happen. The following is the correct way to do what you want:
Code:
char s[] = "This is my String";
s[3] = 'a';
This works correctly, since an array is writable (you can change any of the values within the array). Note the difference in red.
Regards,
Paul McKenzie
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|