8

I am trying to figure out why I can't store characters into my char pointer by using the strcpy() command. I get a seg fault when I run the code below.

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

int main(int argc, const char *argv[])                                               
{                                                                                    
   char *str1, *str2;                                                               
   int ret;                                                                         

   strcpy(str1, "abcdefg"); // stores string into character array str1              
   strcpy(str2, "abcdefg");                                                         

   printf("contents of %s \n", str1);                                               

   ret = strncmp(str1, str2, strlen(str2)); /* compares str1 to str2 */             

   if (ret > 0) {                                                                   
       printf("str1 is less than str2\n");                                          
  }                                                                                
  else if (ret < 0) {                                                              
      printf("str2 is less than str1\n");                                          
  }                                                                                
  else if (ret == 0) {                                                             
      printf("str1 is equal to str2\n");                                           
  }                                                                                

  return 0;                                                                        
  }   

Thank you!

3
  • 2
    Did you try searching the web for strcpy? There's lots of documentation describing how to use it.
    – Bryan Ash
    Oct 13, 2013 at 5:29
  • You can, since the pointer points to anything.
    – The Mask
    Oct 13, 2013 at 5:48
  • I mean points to something, i.e., it's initialized.
    – The Mask
    Oct 13, 2013 at 6:04

3 Answers 3

12

Right now, str1 and str2 are just pointers to a character. When you do strcpy(str1, "abcdefg"), it attempts to write the characters in the string "abcdefg" into the memory that str1 points to and since str1 points to an unknown memory, which probably you don't have any write permissions, you get a segmentation fault.

One way to fix it is to allocate memory on the heap and then store these strings.

#include <stdlib.h>
...
/* assuming the max length of a string is not more than 253 characters */
char *str1 = malloc(sizeof(char) * 254);
char *str2 = malloc(sizeof(char) * 254);

You can also use strdup to duplicate the string like Gangadhar has mentioned.

Another way is to declare str1 and str2 as arrays during the compiling as Bryan Ash suggested

char str1[] = "abcdefg";              
char str2[] = "abcdefg";

In case, you want to allocate the string dynamically but not on the heap, you can use alloca (for more details read http://man7.org/linux/man-pages/man3/alloca.3.html) as kfsone noted

7
  • Using sizeof char is unnecessary, it is 1 by definition in standard. Also using calloc or setting first index to 0 after malloc is a good idea to avoid mistakes with unterminated strings.
    – hyde
    Oct 13, 2013 at 5:33
  • Thanks guys! This site is pretty awesome!
    – Al V
    Oct 13, 2013 at 5:41
  • Someone still use sizeof(char) because it may change in new standards, as times goes on
    – The Mask
    Oct 13, 2013 at 5:49
  • @boaz322 I am wondering why I get the the follow "warning: incompatible implicit declaration of built-in function ‘malloc’ [enabled by default] char *str1 = malloc(sizeof(char) * 254); "
    – Al V
    Oct 13, 2013 at 5:53
  • 1
    you have to add #include <stdlib.h> :) Oct 13, 2013 at 6:15
3

compiling this with the -Wall command gives a useful hint

test.c:12:10: warning: 'str1' is used uninitialized in this function [-Wuninitialized]
    printf("contents of %s \n", str1);
          ^
test.c:14:17: warning: 'str2' is used uninitialized in this function [-Wuninitialized]
    ret = strncmp(str1, str2, strlen(str2)); /* compares str1 to str2 */
2
  • I Think This is a great way to answer a question like this! But maybe also tell how to initialize strings, it is a bit unintuitive in C.
    – hyde
    Oct 13, 2013 at 5:29
  • @hyde thanks when i first started out with C/C++ i wish i knew this earlier
    – pyCthon
    Oct 13, 2013 at 5:30
2

Given this example, you don't even need strcpy, you could use:

char str1[] = "abcdefg";              
char str2[] = "abcdefg";

If you want to learn more about pointers, there's an excellent free e-book titled Pointers and Memory from Stanford CS Education Library.

1
  • I learned pointers yesterday, and I want to really get a hang of it, so I'm starting to try and use them in all of my programs.
    – Al V
    Oct 13, 2013 at 5:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.