Thread: This should not give me a seg fault. Yet.....it does.

  1. #1
    Registered User
    Join Date
    Mar 2012
    Posts
    5

    This should not give me a seg fault. Yet.....it does.

    Code:
    #include <stdio.h>
    #include <string.h>
    char* strconcatenate(char *to, const char *from);
    int main()
    {
    
    
       char* hello= "Hello ";
       const char* world= "World!";
       fprintf(stderr, "%s\n", strconcatenate(hello, world));
       return 0;
    }
    
    
    
    
    char* strconcatenate(char *to, const char *from)
    {
       while((*to) != '\0')
       {
          printf("Execute\n");
          to++;
       }
       while((*from) != '\0')
       {
          printf("Execute2\n");
          *to++ = *from++;
       }
       *to = 0;
       printf("Gotcha\n");
       return to;
    }

  2. #2
    Registered User
    Join Date
    Mar 2012
    Posts
    5
    It will print execute 2 once and that's it. WHYYYYY????!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  3. #3
    Registered User
    Join Date
    Mar 2011
    Posts
    546
    you don't have room in your 'to' string for the extra characters so it is overrunning. change the declaration of hello to char hello[MAX SIZE YOU EXPECT] = "Hello";

  4. #4
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    what makes you think that this "should not" give you a seg fault? you're not allocating any space for the string you're adding to the first.

    and try not to use so much punctuation. its serves no purpose. we understand that you are confused, and the excessive punctuation is unpleasant to look at, and makes you look like a n00b.

  5. #5
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    And the string literal "Hello " may be stored in memory that you're not allowed to write to.
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Why does this malloc give me a segmentation fault?
    By Xpl0ReRChR in forum C Programming
    Replies: 14
    Last Post: 01-09-2012, 12:05 PM
  2. can someone give me an example...
    By micha3lsaint in forum C++ Programming
    Replies: 1
    Last Post: 01-12-2008, 06:06 AM
  3. Replies: 1
    Last Post: 06-29-2004, 05:23 PM
  4. I give up! can someone help me out please?
    By Marcos in forum C++ Programming
    Replies: 14
    Last Post: 01-30-2003, 08:41 PM
  5. segmentation fault and memory fault
    By Unregistered in forum C Programming
    Replies: 12
    Last Post: 04-02-2002, 11:09 PM