Felicia Felicia - 28 days ago 9
C Question

copy a string to an array -- strcpy segfault

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



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,