I'm trying to parse a C array of strings, assigning a part of the words to one array of strings, and the other part to another array. But when I use the strcpy function, I get segfault. Any idea how to solve this?
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char **one = malloc(16 * sizeof(char*));
char **two = malloc(32 * sizeof(char*));
one[0] = "string";
strcpy(two[0], one[0]);
printf("%s\n", two[0]);
}
as a result of compiling and running this, I get segfault.
The array
twoholds space for 32 character pointers after themalloc. However, these pointers are uninitialized and do not point to valid allocated memory at this point.Therefore, the
strcpyessentially has a destination (two[0]) which is some unknown, uninitialized value. A pointer is essentially a value stored in memory. In this case, the value is grabage.The write to a garbage address by
strcpygenerates a SEGFAULT due to the illegal memory access.To resolve this, make sure that the destination (
two[0]) points to a legitimate, writable buffer (perhapstwo[0] = malloc(128 * sizeof(char))).On a related note, look up the similar (but safer) function
strncpy.