开发者

Referencing pointers after a fork() call in C

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 p开发者_如何学Goarent 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...


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! */


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜