c - 如何修复终端中的段错误?

标签 c linux segmentation-fault

Output of the program

我正在尝试编译我的代码,我觉得它工作得很好,我可以编译它。但是,当我这样做时,我遇到了段错误,而且我看不到错误在我的代码中的位置。

我得到的错误是段错误: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);
}

最佳答案

只有在我没有传递任何参数时才会出现段错误,因为

int n = atoi(argv[1]);

本质上会执行 atoi(NULL),因为 argv[1] 会是 NULL

if (argc != 2){
        fprintf(stderr, "usage: %s <starting value>\n", argv[0]);
        return 1; // <- you forgot this!
}

用不同的值调用你的程序不会导致段错误,我已经 尝试使用不同的数字。

另一个错误:main 函数应该定义为:

  • int main(void);
  • int main(int argc, char *argv[]);
  • int main(int argc, char **argv);

你应该改变它。参见 What should main() return in C and C++?

一般信息。如果你想退出一个 void 函数,你所拥有的 要做的是使用没有任何值的 return;,像这样:

void foo(void)
{
    do_some_work();

    if(should_i_terminate)
        return;

    keep_doing_work();
}

关于c - 如何修复终端中的段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48613197/

相关文章:

c++ - 有没有人能够正确使用 libsensors?

c - 推送函数C语言中堆栈中的段错误

c++ - 动态内存分配如何在运行时分配内存?

c - C 中函数不返回任何值时的返回值

linux - 等待队列与 Linux 中的信号量

C++链表在删除具有重复值的节点时会出现段错误

c++ - 无法为堆栈框架生成反汇编,因为无法翻译 URL & 段错误 : 11

c - Postfix运算符的优先级确实比前缀高吗?

编译器会生成无用的汇编代码吗?

linux - 在 Azure Web App 中跨 docker 重启保留内容