Why does this code crash?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Why does this code crash?

  1. #1
    Join Date
    May 2005
    Location
    UK
    Posts
    20

    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

  2. #2
    Join Date
    Apr 1999
    Posts
    27,422

    Re: Why does this code crash?

    Quote Originally Posted by silentray View Post
    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
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center