我已经阅读了这种类型的其他问题,但我仍然无法弄清楚为什么在我的代码中发生了这个错误.
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int len;
int str[0];
} bit_str;
bit_str * input(void);
void print_bitstr(bit_str * s);
int main(void)
{
bit_str * s1 = input();
print_bitstr(s1);
return 0;
}
bit_str * input(void)
{
bit_str *s = (bit_str *) malloc(sizeof(bit_str));
int count = 0, bit;
while ((bit = getchar()) != 'k'){
s = (bit_str *) realloc(s, sizeof(*s) + sizeof(int));
s->str[count++] = bit - 48;
}
s->len = count;
return s;
}
void print_bitstr(bit_str * s)
{
for (int i = 0; i < s->len; i++)
printf("%d ", s->str[i]);
printf("\n");
return;
}
Run Code Online (Sandbox Code Playgroud)
这段代码是我尝试将两个字符串串在一起的程序的一部分(作为数据结构书中的练习).
我创建了一个结构,用于存储位字符串及其长度.使用输入函数中的malloc初始化结构.每次添加新位时都会重新分配.使用getchar读取位,并使用字母"k"划分位串的末尾.
当我编译代码时,它完全适用于6位.但是,如果我尝试输入7位,它会崩溃并出现以下错误:
> realloc(): invalid next size
Run Code Online (Sandbox Code Playgroud)
我已经阅读了其他类似错误的帖子,但我无法弄清楚为什么我的代码中出现此错误.我已经确定当我重新分配时,我使用sizeof运算符来获取大小,而不是绝对值.
有人可以帮我弄清楚我在这里做错了什么吗?
sizeof(*s)在编译时进行评估; 它不知道动态分配,如malloc或realloc.
因此,即使您尝试动态地将sizeof(int)字节添加到当前分配:
s = (bit_str *) realloc(s, sizeof(*s) + sizeof(int));
Run Code Online (Sandbox Code Playgroud)
这总是导致s指向sizeof(bit_str) + sizeof(int)字节.
当然,在no-op之后realloc,您继续向缓冲区写入更多字节,超出缓冲区并导致未定义的行为.