【发布时间】:2018-01-09 22:48:27
【问题描述】:
有人能解释一下这个错误吗?
我收到了错误,直到一时兴起,我改变了这一行:
char *tmp = realloc(str, sizeof(char)*length);
// to added 1
char *tmp = realloc(str, sizeof(char) * length + 1);
我认为将sizeof(char) 乘以长度会重新分配size=sizeof(char)*length 的新内存区域。我不明白为什么添加 1 可以解决问题。
void edit_print(char *inputStr, size_t space_size) {
size_t ch_position = 0;
size_t space_column_count = 0;
size_t num_spaces_left = 0;
while ((inputStr[ch_position] != '\0')) {
if ((inputStr[ch_position] == '\t') && (space_size !=0)) {
num_spaces_left = (space_size-(space_column_count % space_size));
if (ch_position == 0 || !(num_spaces_left)) {
for (size_t i=1; i <= space_size; i++) {
putchar(' ');
space_column_count++;
}
ch_position++;
} else {
for (size_t i=1; i <= num_spaces_left; i++) {
putchar(' ');
space_column_count++;
}
ch_position++;
}
} else {
putchar(inputStr[ch_position++]);
space_column_count++;
}
}
printf("\n");
}
int main(int argc, char *argv[]) {
size_t space_size_arg = 3;
int inputch;
size_t length = 0;
size_t size = 10;
char *str = realloc(NULL, sizeof(char) * size);
printf("Enter stuff\n");
while ((inputch = getchar()) != EOF) {
if (inputch == '\n') {
str[length++] = '\0';
//changed line below
char *tmp = realloc(str, sizeof(char) * length + 1);
if (tmp == NULL) {
exit(0);
} else {
str = tmp;
}
edit_print(str, space_size_arg);
length = 0;
} else {
str[length++] = inputch;
if (length == size) {
char *tmp = realloc(str, sizeof(char) * (size += 20));
if (tmp == NULL) {
exit(0);
} else {
str = tmp;
}
}
}
}
free(str);
return 0;
}
编辑:我最初收到的错误消息是这篇文章标题中的错误消息。进行chux建议的更改后,错误为“realloc(): invalid next size: *hexnumber**”
【问题讨论】:
-
建议让我们了解“错误”可能有助于找出问题所在。
-
我的猜测:
edit_print包含缓冲区溢出错误。你通过给它一些额外的空间来掩盖这个错误。 -
OT:这并不能解释错误,但
sizeof(char) * length + 1在语义上是不正确的。sizeof()应该乘以length + 1的总和。但是因为,在这种情况下,sizeof(char)==1--> 没问题。 -
首先,“sizeof(char)”被定义为1,所以到处都是无关紧要和多余的。然后,似乎对您分配的所有这些内存执行任何操作的唯一代码是 edit_print(),您没有向我们展示。
-
@LeeDanielCrocker 我添加了函数
标签: c memory-management malloc realloc