gpt4 book ai didi

c - 'pre' - 分配指针但尚未使用是什么意思?

转载 作者:太空宇宙 更新时间:2023-11-04 05:57:39 25 4
gpt4 key购买 nike

我正在全局 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;
}

如评论中所述,代码无需重新分配指针即可正常工作 - 这是否意味着我可以将任意多的数据存储到指针中而无需重新分配内存?

为什么我在重新分配 p 时会出现堆损坏?和设置 p_size <= 13在 for 循环中,否则不是?

最佳答案

你的所作所为非常危险。您正在为一个 1 字节的 unsigned char 分配足够的空间,然后您正在写入任意数量的数据。幸运的是你的程序没有每次都崩溃。这是 buffer overflow .

您需要提前分配足够的内存来保存您要写入的数据。如果您无法提前预测,则需要在 func() 调用期间检查您是否有足够的剩余空间,如果没有,则重新分配或中止。

关于c - 'pre' - 分配指针但尚未使用是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24328861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com