我将一些未知大小的数据存储在全局unsigned char
指针变量中,在函数中执行此操作。成功存储数据后,我实际上可以告诉数据大小。如果是这样,我是否需要使用实际指针大小重新分配指针?
出于可行性原因,首先使用p = malloc(sizeof(unsigned char));
分配指针。如果没有这个,我会遇到段错误,但我不明白为什么这是必要的。
示例:
static void func();
unsigned char *p;
int p_size=0;
int main()
{
p = malloc(sizeof(unsigned char)); // Why exactly is this necessary?
func();
/* everything is fine - so do I need reallocation of p
with now knowing the size p_size ?*/
p = realloc( p , p_size * sizeof(unsigned char));
return 0;
}
static void func(){
/*if reallocating p and p_size <= 13, i get heap corruption;
"realloc():invalid next size:..." Otherwise if not reallocating p
I get no errors and p_size is increasable as desired*/
for(p_size; p_size <= 12; p_size++)
*(p + p_size) = 'A' + p_size;
}
正如评论中所述,代码工作正常而没有重新分配指针 - 这是否意味着,我可以将尽可能多的数据存储到指针中,而无需重新分配内存?
为什么在for循环中重新分配p
并设置p_size <= 13
时会出现堆损坏,否则不会?
答案 0 :(得分:4)
你在做什么是非常危险的。您正在为单个unsigned char
分配足够的空间,即1个字节,然后您将编写任意数量的数据。只是运气,你的程序每次都不会崩溃。这是buffer overflow。
您需要提前分配足够的内存来保存您要写的数据。如果您无法提前预测,那么您需要在func()
电话会议期间检查您是否有足够的空间,如果没有,则重新分配或中止。
答案 1 :(得分:1)
*(p + p_size) = 'A' + p_size;
崩溃是因为你试图在这里取消引用NULL指针。 * p被定义为全局变量,因此由编译器自动初始化为NULL。如果在解除引用之前使用malloc * p设置为正确的值。除此之外,您的代码还有两个问题: