1

I keep getting a segmentation fault when I try to copy "init" into my string array, and I can't figure out why. If I comment out the strcpy() line, I don't get a segmentation fault and init prints fine.

    FILE *fp = fopen(argv[1],"r");
    char *init = readToken(fp);
    printf("%s",init);      
    char **words =  malloc(sizeof(char*) * 2); 
    strcat(*words,init);

PS: readToken is an fscanf.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93

2 Answers2

0
 char **words =  malloc(sizeof(char*) * 2); 

Why are you using a double pointer?

Anyway, if you want to pass *words to strcat as destination, you have to allocate it, since the above line just allocates memory for char **words, but when you dereference it you have a pointer which points to an undefined area of the memory

bznein
  • 908
  • 7
  • 21
0

You allocate an array of char *s:

char **words =  malloc(sizeof(char*) * 2); 

These char *s point to nothing in particular. They might be NULL, they might be pointing into the stack, who knows. They're uninitialized and undefined.

strcat(*words,init);

Is like saying

strcat(words[0], init);

If words[0] already pointed to some sort of valid string, this would work. As it is, you're appending a string to some unknown point in memory.

strcpy(*words, init);

Just writes the string into that unknown point in memory, so that won't help.

You need to allocate space for your new string. The simplest way is through strdup(), which makes a copy of the passed in string. So:

*words = strdup(init);

will do fine, as would

words[0] = strdup(init);
Paul Roub
  • 36,322
  • 27
  • 84
  • 93