I have multiple pointers pointing to dynamically allocated memory which was assigned using single malloc.
int *p1, *p2;
p1 = (int*)malloc(sizeof(int) * 10);
p2 = &p1[5];
free(p2);
p1[5] = 3;
p1[6] = 5;
Now my question is what does 'free(p2)' statement would do? Will it free memory ahead p1[5]? Is it safe to use memory ahead p1[5](ie p1[6], p1[7] , . .)
Freeing a pointer that wasn't malloc
/ calloc
ed is undefined behavior. Some allocators such as glibc's can sometimes detect it and deterministically crash the program with a free(): invalid pointer
error message, but technically you lose any and all guarantees about your program's behavior if you do it.
From the reference:
Deallocates the space previously allocated by
malloc()
,calloc()
,aligned_alloc
, (since C11) orrealloc()
.If
ptr
is a null pointer, the function does nothing.The behavior is undefined if the value of
ptr
does not equal a value returned earlier bymalloc()
,calloc()
,realloc()
, oraligned_alloc()
(since C11).—
free
, C++ Reference
Emphasis mine: your use of free
in this context would involve freeing from a pointer that was not obtained from the use of any of those functions; it was obtained by transforming the pointer that was obtained from malloc
, and thus is not valid.
My best guess at what might happen is a segmentation fault; but that's up to your compiler, and not something you or I can guarantee.
So do not do this.
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.