【发布时间】:2019-03-06 21:42:01
【问题描述】:
我写了这段代码,但是在字符串的开头插入了垃圾:
void append(char *s, char c) {
int len = strlen(s);
s[len] = c;
s[len + 1] = '\0';
}
int main(void) {
char c, *s;
int i = 0;
s = malloc(sizeof(char));
while ((c = getchar()) != '\n') {
i++;
s = realloc(s, i * sizeof(char));
append(s, c);
}
printf("\n%s",s);
}
我该怎么做?
【问题讨论】:
-
只需在
s = calloc(1, sizeof(char))上更改s = malloc(sizeof(char))或在malloc*s = '\0';之后添加新行 -
不要尝试在长度为 1 的缓冲区中存储 2 个字符。
-
s[len+1] = '\0';超出分配的内存范围。在第一次调用中,没有一个有效的字符串可以将strlen应用到。 -
@Weather Vane,是的,但他是个聪明人;他在 append() 之前使用 reallock()
-
@purec 此时分配的内存大小为
1,并且可能不包含字符串所需的终止0。它需要为2的大小并被初始化。