Thread: Pointing at a string gave me segmentation fault

  1. #1
    Registered User
    Join Date
    Jun 2012
    Location
    Göteborg
    Posts
    28

    Pointing at a string gave me segmentation fault

    I'm trying to figure out how to use pointers and strings. I get segmentation fault when I run this program. I just don't understand why. I'm using gcc version 4.4.3 (Ubuntu).

    Code:
    #include <stdio.h>
    
    char *my_strcpy(char *destination, char *source) {
    
      char *p = destination;
    
      while (*source != '\n') {
        *p++ = *source++;
      }
      *p = '\0';
      return destination;
    }
    
    char strA[80] = "Test string";
    char strB[80];
    
    int main(void) {
    
      char *pA;     // a pointer to type character
      char *pB;
      char *pC;
    
      pA = strA;    // point pA at string A
      pB = strB;
    
      pC = my_strcpy(strB,strA);
      
      return 0;
    }

  2. #2
    Registered User
    Join Date
    May 2012
    Location
    Arizona, USA
    Posts
    948
    Where is the newline character in your source string?

  3. #3
    Registered User
    Join Date
    Jun 2012
    Location
    Göteborg
    Posts
    28
    Newline? I'm not sure what you mean here. Do you mean "\n" at row 10?

  4. #4
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Yes, the '\n'. That is what stops your loop, when it finds a newline in the source string. But if there's no newline, you have an infinite loop. Why not stop when you find the null character in source? That is what officially ends a string in C anyhow.

  5. #5
    Registered User
    Join Date
    Jun 2012
    Posts
    8
    Try to do this on line 7, at the end of a string goes a '\0'

    Code:
    while (*source != '\0') {

  6. #6
    Registered User
    Join Date
    Jun 2012
    Location
    Göteborg
    Posts
    28
    Ahhh. Of course pablo9891. Typo at row 7. I'm blind. Thank you for all your help.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Segmentation fault when comparing dynamic string to literal
    By screennameless in forum C++ Programming
    Replies: 13
    Last Post: 06-29-2011, 02:09 AM
  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