Thread: Too long string causes segmentation fault

  1. #1
    Registered User
    Join Date
    Jun 2012
    Location
    Here
    Posts
    23

    Too long string causes segmentation fault

    Hello.

    This simple code was nicely working:

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(void)
        {
        char *source_str = "Some message here.\n";
        char str[strlen(source_str) * 2];
        int i;
    
        strcpy(str, source_str);
    
        for(i=0; i<5; i++)
            strcat(str, source_str);
    
        printf("%s\n", str);
    
        return 0;
        }
    Then I made some changes in the string:

    Code:
    char *source_str = "Some message here."
        " Let's make it even longer."
        " Let's add another sentence.\n";
    Now, when I try to run this program, system replies: "Segmentation fault"

    What actually causes this an what would be the alternatives?

    Thank you.

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Quote Originally Posted by heinz55 View Post
    This simple code was nicely working:
    That doesn't mean there were no bugs.
    The string str is not large enough.
    try
    Code:
    char str[strlen(source_str) * 6 + 1];
    Kurt

  3. #3
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    They are both errors, but the first one doesn't write far enough beyond the end of the array to cause a segfault.

    Why are you apparently setting aside space for two copies and then putting in five copies?

    Code:
    #include <stdio.h>
    #include <string.h>
    
    #define REPEAT 5
    
    int main(void)
        {
        char *source_str = "Some message here.\n";
        char str[strlen(source_str) * REPEAT + 1];
        int i;
    
        strcpy(str, source_str);
    
        for(i=0; i<REPEAT; i++)
            strcat(str, source_str);
    
        printf("%s\n", str);
    
        return 0;
        }
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  4. #4
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,907
    Code:
    
    char *source_str = "Some message here."
        " Let's make it even longer."
        " Let's add another sentence.\n";

    Did you put this in your code character by character?... Where did you get the idea that you could do that? Even if it did put it in memory, the "" puts a NULL character at the end of the first string, so strlen wouldn't count past that character.


    If you want a few different stings in the same variable, you need to create an array of strings. Like section 6 of http://www.thegeekstuff.com/2011/12/c-arrays/
    Last edited by Click_here; 08-07-2012 at 12:19 AM. Reason: Failed to upload first time

  5. #5
    Registered User piyush.sharma's Avatar
    Join Date
    Aug 2012
    Location
    Noida, India
    Posts
    9
    This is an undefined behavior, so we can't predict the output. You can view this warning if you enable -pedantic flag of gcc.
    ISO C90 forbids variable-size array ‘str’

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Click_here
    Did you put this in your code character by character?... Where did you get the idea that you could do that? Even if it did put it in memory, the "" puts a NULL character at the end of the first string, so strlen wouldn't count past that character.
    Actually, adjacent string literals are concatenated, so this code:
    Code:
    char *source_str = "Some message here."
        " Let's make it even longer."
        " Let's add another sentence.\n";
    is equivalent to:
    Code:
    char *source_str = "Some message here. Let's make it even longer. Let's add another sentence.\n";
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    char *source_str = "Some message here.\n";
    [Edit]
    I was thinking about C++ here so disregard this bit.
    [/Edit]

    This used to be deprecated, but I think it is now simply illegal.

    The actual string is a constant literal; the pointer to such a beast must be a pointer to a constant.

    Where did you get the idea that you could do that?
    You can do that.

    Actually, for portable code using the integer specific stuff from "C99" you must occasionally do something like that.

    Anyway, the strings are concatenated by the compiler into one long string.

    This is an undefined behavior, so we can't predict the output.
    The original post didn't say it was supposed to be "C90". It is a feature of "C99".

    The code does exhibit undefined behavior, but not necessarily because of the variable-length array.

    Soma

  8. #8
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by phantomotap View Post
    This used to be deprecated, but I think it is now simply illegal.

    The actual string is a constant literal; the pointer to such a beast must be a pointer to a constant.
    Not true. Initialising a non-const char pointer to a string literal is still deprecated in C11. Using that pointer to modify the literal gives still undefined behaviour.

    This is a feature that has existed since K&R C, so it is very firmly entrenched in C, and - practically - is used in a large amount of code. It will therefore take a considerable period of time to remove it. That explains why it has been deprecated in more than one C standard, but not yet removed. It could well remain in the "deprecated but still legal" category through several more evolutions of the C standard. It takes time to remove firmly entrenched features from a standard.

    Quote Originally Posted by phantomotap View Post
    The code does exhibit undefined behavior, but not necessarily because of the variable-length array.
    Indeed. The code exhibits undefined behaviour because the data being copied is longer than the allocated buffer. That would be equally true whether the code uses a VLA, dynamic memory allocation, or a static array with length determined at compile time.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  9. #9
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,907
    I never new that you could do that -> It seems illogical to me, but I'm always happy to learn.
    Last edited by Click_here; 08-07-2012 at 06:13 AM. Reason: I had a problem, but I worked it out.

  10. #10
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    Initialising a non-const char pointer to a string literal is still deprecated in C11.
    O_o

    I was thinking of C++.

    See the "[Edit][/Edit]" note that was added a couple of hours before you posted.

    Soma

  11. #11
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by Click_here View Post
    I never new that you could do that -> It seems illogical to me, but I'm always happy to learn.
    Welcome to "compile-time string concatenation".

    Very handy when you want to do things like:
    Code:
    printf("We are in the "__FUNCTION__ " function!");
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  12. #12
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,907
    This is a great thing to know

    Code:
    
    
        const char *compile_information = "Compiled: \n\r\t" __TIME__ "\n\r\t" __DATE__"\n\rFile:\n\r\t" __FILE__ ;
    I'm so happy that I got involved with this forum -> I'm learning so much.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointing at a string gave me segmentation fault
    By hzcodec in forum C Programming
    Replies: 5
    Last Post: 06-14-2012, 03:58 PM
  2. String assignment segmentation fault (core dump)
    By kapil1089thekin in forum C++ Programming
    Replies: 19
    Last Post: 08-07-2010, 12:51 AM
  3. Segmentation fault when changing a string
    By lilydjwg in forum C Programming
    Replies: 6
    Last Post: 12-02-2009, 07:43 AM
  4. segmentation fault when processing a string
    By Nakel in forum C++ Programming
    Replies: 2
    Last Post: 04-24-2003, 04:02 PM
  5. segmentation fault when processing a string
    By EMC2 in forum C++ Programming
    Replies: 0
    Last Post: 04-24-2003, 02:56 PM

Tags for this Thread