【问题标题】:Segmentation fault in number printing program号码打印程序中的分段错误
【发布时间】:2013-05-18 05:05:07
【问题描述】:

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

#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;
}

【问题讨论】:

标签: c segmentation-fault


【解决方案1】:

这是因为??/ 是一个三元组,它变成了\,导致您的exe = malloc... 行变成了评论的一部分。因此,exe 仍然为 NULL,并且在您取消引用它时会崩溃。

【讨论】:

  • +1 嗯,哇。我不知道这是一个合理的问题,还是我们只是受到了攻击。
  • 我的钱花在了 OP 上,只是阅读了另一个特别提到的三元组问题。
  • 真的不错。完全错过了三字。
  • 哈哈,很好,想知道有多少人知道三元组。在我问这个问题后不到 10 分钟,有人发布了正确的答案,这让我感到惊讶。是的,我事先确实知道三元组(查看完美对齐的评论:P),但了解三元组并小心它们绝对是件好事。恭喜,先生,您得到了我的支持并接受了。
  • 如果您不包含整个程序,而只包含前面的有趣注释的两行代码,这个问题可能会稍微令人费解。我剪切并粘贴了整个程序,GCC 默认会警告三元组。
【解决方案2】:

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

【讨论】:

  • 不,那是argv[0],而不是argv[1]。这样,它就是程序的名称。
  • "如果 src 的长度小于 n,strncpy() 将额外的空字节写入 dest,以确保总共写入 n 个字节。"
【解决方案3】:

您需要确保您的exe 字符串在您strncpy 之后有一个NULL 终止符。

尝试在strncpy之后添加这一行:

    exe[49] = '\0';

【讨论】:

  • strncpy 添加了一个 NULL 终止符...另外,strncpy 函数本身会导致段错误。
  • strncpy 仅在第一个 n (在您的情况下为 49 个)字符中添加一个 NULL 终止符。否则,它不会。
猜你喜欢
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-28
  • 1970-01-01
  • 1970-01-01
  • 2021-01-29
相关资源
最近更新 更多