在 C 中调用 fork() 后引用指针
因此,我有一个函数可以加载带有一些字符串数据的 char** 变量。我的目标是分叉该进程,并在子进程中打印一些数据,并从父进程中打印一些数据。但是,我无法在 fork() 调用后引用指针。
我认为 fork() 复制了父进程的整个地址空间,这似乎会包括各种堆栈指针......
本质上,我的代码目前看起来像这样:
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! */
任何人都知道我在做什么错误的?我对此进行了一些谷歌搜索,看起来我正在做的事情应该有效 - 但事实并非如此。因此,我误解了一些基本的东西......
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在执行错误的指针操作,并且在第一次调用时很幸运 - 代码应如下所示:
You're doing bad pointer operations and just getting lucky on the first call - here's what the code should look like:
在您的情况下,
data
不指向任何地方。 使用未初始化的变量是未定义的行为。即使它在 load_data 函数内部发生更改,该更改也不会在外部可见。您需要使
data
指向有效的内容,或者将data
的地址传递给函数以使更改“返回”,如load_data(char ***数据)
。您的代码只需进行最少的更改即可成为一个完整的程序,对我来说“有效”
并且可以运行示例
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