【发布时间】: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