【发布时间】:2022-11-15 02:15:12
【问题描述】:
我试图从 C 中的标准输入读取一行,同时使用下面的代码 sn-p 为字符串动态分配内存。问题是,当我运行这段代码时,调用strlen(msg)之类的东西会在 valgrinds 输出中产生Conditional jump or move depends on uninitialised value(s)。
我不明白如何解决这个问题,因为如果我动态分配它,我将无法正确初始化它。我现在已经在这上面花了很长时间,但似乎无法弄清楚……任何帮助将不胜感激。
char* msg = NULL;
int c;
// set initial size for dynamic allocation
msg = malloc(sizeof(char)*10+1);
int idx = 0;
char* temp = NULL;
size_t size = 10;
while (1){
c = getchar();
if(c == EOF || c == '\n'){
break;
}else if(!isalpha(c)){
free(msg);
exit(100);
}
// dynamically reallocate memory if input too large
if(size <= idx){
size += size;
temp = realloc(msg, size);
msg = temp;
}
msg[idx++] = (char)c;
}
printf("%ld", strlen(msg));
【问题讨论】:
标签: c valgrind dynamic-memory-allocation