JWD*_*WDN 1 c memory free pointers
我正在调整数组的指针以避免向后复制数组的所有内容。问题是我想在某个时刻释放数据,这将产生分段错误,除非我将指针移回其原始地址。有什么办法可以避免这种情况吗?因为如果移位是在函数内部执行的,则调用函数可能不知道移位的幅度。
例子:
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
Run Code Online (Sandbox Code Playgroud)
我在这里期待太多了吗?
这不可能。传递给的指针free()
必须从动态分配函数之一返回。从free()
参考页面:
释放先前由 malloc()、calloc() 或 realloc() 分配的空间。如果 ptr 是空指针,则该函数不执行任何操作。
如果 ptr 与 malloc()、calloc() 或 realloc() 先前返回的指针不匹配,则行为未定义。此外,如果 ptr 引用的内存区域已被释放,即已使用 ptr 作为参数调用了 free() 或 realloc(),并且未调用 malloc()、calloc() 或,则行为未定义。 realloc() 之后产生一个等于 ptr 的指针。
因为如果移位是在函数内部执行的,则调用函数可能不知道移位的幅度。
如果指针按值传递,则不是问题,对指针的任何修改对于调用者来说都是不可见的:
void f(char* a_ptr) { a_ptr++; }
char* p = malloc(10);
f(p);
free(p); /* Valid as no change was made to 'p'. */
Run Code Online (Sandbox Code Playgroud)