gpt4 book ai didi

c - 如何使用已调整的指针安全地释放内存

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

我正在调整数组的指针以避免向后复制数组的所有内容。问题是我想在某个时候释放数据,这将产生一个段错误,除非我将指针移回它的原始地址。有什么办法可以避免这种情况吗?因为如果移位是在函数内部执行的,调用函数可能不知道移位的大小。

示例:

int i;
float * y = malloc(10*sizeof(float));

for(i=0;i<10;i++) y[i] = (float)i;

y += 2;

for(i=0;i<8;i++) printf("%d\n",y[i]);

free(y); // this will generate a segmentation fault
y -= 2; free(y); // this is OK, but I would like to avoid it

我是不是期望太高了?

最佳答案

这是不可能的。传递给 free() 的指针必须从动态分配函数之一返回。来自free()引用页:

Deallocates the space previously allocated by malloc(), calloc() or realloc(). If ptr is null-pointer, the function does nothing.

The behavior is undefined if ptr does not match a pointer returned earlier by malloc(), calloc() or realloc(). Also, the behavior is undefined if the memory area referred to by ptr has already been deallocated, that is, free() or realloc() has already been called with ptr as the argument and no calls to malloc(), calloc() or realloc() resulted in a pointer equal to ptr afterwards.


Because if the shift is performed inside a function, the calling function might not be aware of the magnitude of the shift.

如果指针是按值传递的,那么调用者将看不到对指针的任何修改:

void f(char* a_ptr) { a_ptr++; }

char* p = malloc(10);
f(p);
free(p); /* Valid as no change was made to 'p'. */

关于c - 如何使用已调整的指针安全地释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16237449/

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