错误:分段故障核心转储

时间:2014-12-14 06:18:12

标签: c

我正在学习操作系统。当我测试这段代码时,我遇到了这个问题 - 分段错误,核心转储。 如何解决这个问题?

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>

int main()
{
    int p,*stat_addr;
    while((p=fork())==-1);
    if(p==0)
        exit(0);
    else
    {
        wait(stat_addr);
        printf("%d\n",*stat_addr);
        exit(0);
    }
}

2 个答案:

答案 0 :(得分:1)

那是因为你还没有初始化stat_addr。做类似的事情:

int stat_addr = 10;

然后像:

一样使用它
wait(&stat_addr);

答案 1 :(得分:0)

使用:

int status;
int corpse = wait(&status);

尸体是死亡孩子的PID(如果没有孩子,则为-1)。退出状态以status编码,除非corpse == -1

因为你有一个未初始化的指针而崩溃。我怀疑你对wait()函数的原型感到困惑:

pid_t wait(int *stat_loc);

是的,它需要一个指针,但它必须是一个初始化为指针点的指针。或者,通常情况下,它是int变量的地址,与我建议用法中的&status一样。

相关问题