0

I am trying to copy a string to an array and print it. It works for the first for loop, but seg faults the second time.

main (int argc, char *argv[]){
 int argcIndex;
 char **argumentArray = NULL;

 for(argcIndex=0; argcIndex < argc; argcIndex++){
     argumentArray = (char**) malloc((argc+1)*sizeof(char*));
     argumentArray[argcIndex] = (char*) malloc(((strlen(argv[argcIndex])+1)*sizeof(char)));
     strcpy(argumentArray[argcIndex], argv[argcIndex]); //Works here
     printf("argumentArray[%d]: %s \n", argcIndex, argumentArray[argcIndex]); //Works here
 }

 for(argcIndex=0; argcIndex < argc; argcIndex++){
     //strcpy(argumentArray[argcIndex], argv[argcIndex]); //This gives me a segfault
     printf("argumentArray[%d]: %s \n", argcIndex, argumentArray[argcIndex]); //This will only grab the last string in array
 }

}

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Felicia
  • 33
  • 1
  • 1
  • 8
  • [Please see this discussion on why not to cast the return value of `malloc()` and family in `C`.](http://stackoverflow.com/q/605845/2173917). – Sourav Ghosh Sep 29 '16 at 14:04
  • @SouravGhosh I took away the cast and the second printf statement still only grabs the last string passed in to the array – Felicia Sep 29 '16 at 14:06

1 Answers1

1

You need to move the allocation for argumentArray

 argumentArray = (char**) malloc((argc+1)*sizeof(char*));

outside the first for loop, otherwise, every iteration, you're overwriting (and finally, leaking) the memory.

The problem underneath that is, malloc() returns uninitialized memory, and for the last iteration, only one index, argc-1 is getting written, so the content of other index remains indeterminate. In the later loop, when you try to use that value, it invokes undefined behavior.

That said,

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • Thank you! I knew it was something about the malloc statement that was causing the error, but didn't know what. Thank you! – Felicia Sep 29 '16 at 14:13