【问题标题】:Segmentation fault (core dumped) - how to fix my code?分段错误(核心转储) - 如何修复我的代码?
【发布时间】:2017-04-05 00:38:58
【问题描述】:

程序在字符串中找到一个ASCII码最小的char并输出。我的问题在消息中:分段错误(核心转储)。为什么和在哪里发生? 感谢关注。

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

int main(void) {    

char* str = NULL;    
int* mincode = NULL;    
int* count = NULL;    
char* mincodeChar = NULL;


 str = (char *) malloc(50 * sizeof(char));
 mincode = (int *) malloc(1 * sizeof(int));
 count = (int *) malloc(1 * sizeof(int));

 if (NULL == str || NULL == mincode || NULL == count){
        printf("Alloc error");
        return EXIT_FAILURE;
    }

fgets(str, 50, stdin);

printf("your string: ");
puts(str);

*mincode = (int)(str[*count]);
*mincodeChar = *(str + *count);

 for (*count = 0; str[*count] != '\0'; (*count)++) {

    if( (int)str[*count] < (*mincode)) {
    (*mincode) = (int)str[*count];
    mincodeChar = (str + *count);
    printf("%c", *mincodeChar);
    }
}

printf("your character: ");
printf("%c", *mincodeChar);

free(str);
free(mincode);
free(count);

return EXIT_SUCCESS;
}

【问题讨论】:

  • 当你有编译时固定大小时,你为什么要动态分配内存?特别是,为什么要为 one int 分配内存?为什么不使用简单的int 变量?
  • 1) *mincode = (int)(str[*count]); : *count 未初始化。
  • 顺便说一句,为什么要分配这么多动态内存? int *count 比普通的 int count 更好吗?
  • 任务里写的——不要用普通的var。所以,这就是为什么
  • 这不是我发布的评论,但您必须记住malloc 只是分配 内存,它不会以任何方式对其进行初始化。因此,当您在循环之前使用 *count 时,您会得到一个可能非常错误的 indeterminate 值,并且您可能会超出为 str 分配的内存范围。

标签: c pointers segmentation-fault coredump


【解决方案1】:
char* mincodeChar = NULL;
....
*mincodeChar = *(str + *count);

你取消引用一个 NULL 指针。

从中吸取的教训是:

  1. 始终尽快将变量初始化为有效值。
  2. 在取消引用之前检查指针。

【讨论】:

  • 但是有 mincodeChar = (str + *count);然后我取消引用 mincodeChar。为什么它仍然不起作用?它会导致问题吗?
  • @Sergei, *mincodeChar = *(str + *count); mincodeChar = (str + *count); 相同。第一个访问指向的值,第二个访问指针。
【解决方案2】:

没有检查但是

*mincode = (int)(str[*count]);
*mincodeChar = *(str + *count);

count 包含未初始化的值。所以它可能是 0,更可能是 492892911039 之类的东西......永远不理解未初始化变量的随机性。在这种情况下,您正试图在 492892911039.... SIGSEGV 处开仓?如果你想要 0 或者明确地将它设置为 0 或者更确切地说是 malloc() 调用 calloc()。然后和其他人一样......为什么你分配一个变量? ...它可能会发生,但是对于外部约束,例如当您调用一些仅接受 void *... 但可以避免的 API 函数时,最好避免。不仅仅是因为懒惰。 malloc 的大多数实现都是列表。因此,您分配的越多,就越长成为这个列表,在每次新分配时都必须进行评分。所以它会减慢你的malloc()。在这种情况下当然不是......但最好分配几个大块内存而不是很多小块

【讨论】:

    猜你喜欢
    • 2020-02-04
    • 2021-06-23
    • 1970-01-01
    • 2022-10-13
    • 2018-04-03
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    相关资源
    最近更新 更多