Referencing pointers after a fork() call in C

2019-07-20 13:51发布

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...

2条回答
我想做一个坏孩纸
2楼-- · 2019-07-20 14:41

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 of data to the function to have the changes "return", as in load_data(char ***data).


Your code, with minimal changes to make it a complete program, "works" for me

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int load_data(char **data);

int main(void) {
  char **data;
  data = malloc(2 * sizeof *data);
  assert(data && "no memory");
  load_data(data);
  printf("String 0: %s\n", data[0]);
  fork();
  printf("String 0 again: %s\n", data[0]);
  return 0;
}

int load_data(char **data) {
  data[0] = "one";
  data[1] = "two";
  return 2;
}

And a sample run

$ ./a.out 
String 0: one
String 0 again: one
String 0 again: one
查看更多
劫难
3楼-- · 2019-07-20 14:46

You're doing bad pointer operations and just getting lucky on the first call - here's what the code should look like:

load_data(char **data);

char* data = NULL;
load_data(&data);
printf("String 0: %s\n", data);
fork(); 
printf("String 0 again: %s\n", data);    /* Doesn't Segfault Here! */
查看更多
登录 后发表回答