【发布时间】:2018-02-04 21:30:31
【问题描述】:
我正在尝试编译我的代码,我觉得它工作得很好,我可以编译它。但是,当我这样做时,我收到段错误错误,我看不到代码中的错误在哪里。
我得到的错误是 Segment fault: 11 我已经查过了,我知道它与内存分配有关,但无法在代码中找到我需要修复我的内存分配并修复我在这里遇到的错误。
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
/*The Main Function Start*/
void main(int argc, char *argv[])
{
/*Storing The Process Id*/
pid_t pid;
int j;
int status = 0;
/*process of forking*/
if (argc == 1){
fprintf(stderr,"Usage: ./hw1 <starting value>\n");
}
int n = atoi(argv[1]);
pid=fork();
if (pid == -1){
printf("Error in forking....\n");
exit(0);
}
/*Child process*/
if (pid == 0)
{
printf("Child PID: %d\n",getpid());
while (n != 1){
printf("%d ",n);
if (n % 2 == 0){
n = n/2;
}
else {
n = 3*n + 1;
}
}
printf("1\n");
}
else{
printf("Parent PID: %d\n",getpid());
/*Waiting for the child to finish*/
wait(0);
}
exit(0);
}
【问题讨论】:
-
当你在没有任何参数的情况下调用它时,你会得到一个
segfault,因为你在打印到stderr之后没有exit或return。atoi(argv[1])是我之前所说的问题。 -
请不要发布终端输出的图片,只需复制并粘贴终端的输出并将其发布到您的代码中。
标签: c linux segmentation-fault