来自 atoi 的段错误

Segfault from atoi

我是编写线程代码的新手,对 C 感到生疏。我已经尝试使用 gdb 进行调试,在我尝试使用 atoi 设置 num 的值后似乎出现了段错误,但我不知道为什么。谁能解释这个段错误?

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>

int *ptr;

int getFibonacciNumber(int num)
{
    if ( num <= 1 ) return num;
    else if ( ptr[num] != 0 ) return ptr[num];
    else{
        int fibOfNMO = getFibonacciNumber(num - 1);
        int fibOfNMT = getFibonacciNumber(num - 2);
        ptr[num] = fibOfNMO + fibOfNMT;
        return ptr[num];
    }
}

void* fibonacci(void* arg)
{
    int* num = (int*)arg;
    int fib = getFibonacciNumber(*(num));

    return NULL;
}

int main(int argc, char** argv)
{
    printf("%s", argv[0]);
    pthread_t tid_main;
    pthread_t tid_fib;
    int ret;
    int* num;
    *num = atoi(argv[0]);

    if ( argv[0] != NULL ) ptr = (int*)malloc((*(num) + 1)*sizeof(int));
    else exit(EXIT_FAILURE);

    int i;
    for (i = 0; i < *(num) + 1; ++i) ptr[i] = 0;
    ptr[1] = 1;

    printf("%d\n", getFibonacciNumber(6));
    ret = pthread_create(&tid_fib, NULL, fibonacci, num);
    if (ret) {
        fprintf(stderr, "error -- pthread_create() failed.\n");
            exit(EXIT_FAILURE);
        }

    ret = pthread_join(tid_fib, NULL);
    if (ret) {
            fprintf(stderr, "error -- pthread_join() failed.\n");
            exit(EXIT_FAILURE);
        }

    printf("%d\n", ptr[*(num)]);
    free(ptr);
    return 0;
}
int* num;
*num = atoi(argv[0]);

取消引用未初始化的指针 - 未定义的行为。

改为

int num;
num = atoi(argv[0]);

int *num = malloc(sizeof(int));
*num = atoi(argv[0]);

Num 是一个指针,不指向任何内容。 在

中更正
int main(int argc, char** argv)
{
    printf("%s", argv[0]);
    pthread_t tid_main;
    pthread_t tid_fib;
    int ret;
    int num;
    num = atoi(argv[0]);

请注意,这意味着整个主要功能代码必须将 num 视为 int 而不是 int *

您遇到段错误是因为 num 未初始化为指向任何内容(或者更确切地说,编译器可能将其设为空指针)。然后您尝试为这个垃圾指针分配一个变量。

您必须 malloc 一些内存供其使用,或者仅将其声明为静态变量并在必要时使用一元 &.

创建指向它的指针
int* num;
*num = atoi(argv[0]);
  1. num 是一个指针,在向其写入内容之前它应该指向某个有效的内存位置。在你的情况下你不这样做所以你看到分段错误。

  2. 如果 argc 大于 0,
  3. argv[0] 将始终是程序的名称。

If the value of argc is greater than zero, the array members argv[0] through argv[argc-1] inclusive shall contain pointers to strings, which are given implementation-defined values by the host environment prior to program startup. The intent is to supply to the program information determined prior to program startup from elsewhere in the hosted environment. [...]

If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name; argv[0][0] shall be the null character if the program name is not available from the host environment. [...]

PS: atoi(NULL) 导致崩溃并且 argv[0] 可能为 NULL。