【发布时间】:2012-10-12 23:25:34
【问题描述】:
我正在刷新我的 C 技能。我正在使用 char *s 并使用 malloc 为 s 分配内存。然后使用scanf,我将输入读取到s。但我的问题是我没有指定内存块的大小。但该程序有效。如何为任意长度的输入字符串分配内存? scanf 是否只是增加指针并将数据写入该位置?
#include <stdio.h>
#include <stdlib.h>
int main() {
char *s;
s = (char *) malloc(sizeof(s)); //I did not specify how much like malloc(sizeof(s) * 128)
if (s == NULL) {
fprintf(stderr, "\nError allocating memory for string");
exit(1);
}
scanf("%s", s);
puts(s);
free(s);
return 0;
}
/*
Input:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Output:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
*/
【问题讨论】:
-
您正在调用未定义的行为。你现在可以侥幸逃脱,但这是一场等待发生的灾难。