Reputation: 33
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
}
}
Upvotes: 0
Views: 655
Reputation: 134346
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,
sizeof(char)
is guaranteed to be 1 in C. There's no point in multiplying anything by it.malloc()
and family in C
..instead of malloc()
and strcpy()
, you can make use of strdup()
, if that's available.
Note: strdup()
is not a standard C function, FWIW.
Upvotes: 1