So, I've got a function that loads up a char** variable with some string data. My goal is to fork the process, and print some of that data in the child, and some from the parent. However, I'm unable to reference the pointer after the fork() call.
I thought that fork() made a copy of the entire address space of the parent process, which seems that it would include the various stack pointers...
Essentially, my code currently looks like this:
load_data(char **data);
char** data;
load_data(data);
printf("String 0: %s\n", data[0]);
fork();
printf("String 0 again: %s\n", data[0]); /* Segfaults Here! */
Anyone have any ideas what I'm doing wrong? I've done a bit of google searching on this, and it seems what I'm doing should work - but it doesn't. Thus, I'm misunderstanding something fundamental...
In your case,
data
doesn't point anywhere. Using an uninitialized variable is undefined behaviour. Even if it changed inside the load_data function, the change wouldn't be visible outside.You need to either make
data
point to something valid, or pass the address ofdata
to the function to have the changes "return", as inload_data(char ***data)
.Your code, with minimal changes to make it a complete program, "works" for me
And a sample run
You're doing bad pointer operations and just getting lucky on the first call - here's what the code should look like: