数字打印程序中的分段错误

时间:2013-05-23 00:28:14

标签: c segmentation-fault

当我运行这个时,我得到一个分段错误?

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

static char* exe;

void usage(void) {
    printf("Usage: %s <number of integers>\n", exe);
}

int main(int argc, char** argv) {
    //This program reads in n integers and outputs them/
    //in reverse order. However, for some odd reason, I/
    //am getting an error when I run it with no command/
    //line arguments. It is supposed to display helpful/
    //usage information out, but instead it segfaults??/
    exe = malloc(50 * sizeof(*exe));
    strncpy(exe, argv[0], 49);

    if(argc != 2) {
        usage();
        exit(0);
    }

    int n = atoi(argv[1]);
    int* numbers = malloc(n * sizeof(*numbers));

    int i;
    for(i = 0; i < n; i++) {
        scanf("%d\n", &numbers[i]);
    }

    for(i = 9; i >= 0; i--) {
        printf("%d:\t%d\n", 10 - i, numbers[i]);
    }

    free(numbers);
    free(exe);
    return 0;
}

3 个答案:

答案 0 :(得分:6)

这是因为??/是变成\的三字符,导致您的exe = malloc...行变成评论的一部分。因此,exe仍为NULL,并在取消引用时崩溃。

答案 1 :(得分:0)

变量argv[0]包含指向您正在运行的程序名称的指针。你的程序试图从这个指针开始读取49个字符,或者读取NULL,以先到者为准。在您的情况下,您可能正在转移到您无权访问的新页面。

答案 2 :(得分:0)

exe之后,您需要确保strncpy字符串有一个NULL终结符。

尝试在strncpy

之后添加此行
    exe[49] = '\0';