简体   繁体   中英

How to safely free memory using a pointer which has been adjusted

I am adjusting a pointer for an array to avoid copying all the contents of the array backwards. The problem is I want to free the data at some point, which will generate a segmentation fault unless I shift the pointer back to it's original address. Is there any way to avoid this? Because if the shift is performed inside a function, the calling function might not be aware of the magnitude of the shift.

Example:

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

Am I expecting too much here?

This is not possible. The pointer passed to free() must be returned from one of the dynamically allocating functions. From the free() reference page:

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.

Not an issue if the pointer is passed by value any modification to the pointer will not be visible to the caller:

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

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

You can use a different variable:

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

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

float *y2 = y+2;

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

free(y);

只需在malloc之后进行float * z = y并在末尾free(z)

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

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

//y += 2; 
float *y2 = y + 2;
for(i=0;i<8;i++) printf("%f\n",y2[i]);

y=realloc(y, 2*sizeof(float));//do free y[2]..y[9]

free(y);//finally

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM