CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Feb 2012
    Location
    INDIA
    Posts
    25

    Unhappy REVERSE_of_STRING...

    I keep getting segfaults when trying to run the code below. It seems Runtime error due to the line the *end = *begin; . Why is that?


    #include <stdio.h>
    #include <string.h>

    void my_strrev(char* begin)
    {
    char temp;
    char* end;
    end = begin + strlen(begin)-1;

    while(end>begin){
    temp = *end;
    *end = *begin;
    *begin = temp;
    end--;
    begin++;
    }
    }

    main()
    {
    char *string = "school";
    my_strrev(string);
    printf("%s", string);
    }
    TANUSHREE-AGRAWAL...

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: REVERSE_of_STRING...

    For your purposes, this is wrong:
    Code:
    char *string = "school";
    It should be:
    Code:
    char string[] = "school";
    Otherwise you have a pointer to the first element of a string literal, and you cannot modify that string literal.

    By the way, please post code in [code][/code] bbcode tags.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  3. #3
    Join Date
    Apr 1999
    Posts
    27,449

    Re: REVERSE_of_STRING...

    Quote Originally Posted by Tanushreeagr View Post
    I keep getting segfaults
    What program written in Visual C++ segfaults?

    Oh, you mean you're running this in Linux or some other OS and not using Visual C++? Then why did you post in the Visual C++ forum? Next time, post such questions in the Non Visual C++ forum.

    If you did compile with Visual C++, the result should have been an unhandled exception (access violation). The reasons being the same as laserlight stated -- it is undefined behaviour to modify a string literal.

    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
  •  





Click Here to Expand Forum to Full Width

Featured