简体   繁体   English

Malloc,free和多个指针,它如何工作?

[英]Malloc, free, and multiple pointers, how does it work?

I have multiple pointers pointing to dynamically allocated memory which was assigned using single malloc. 我有多个指针指向使用单个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? 现在我的问题是'free(p2)'语句会做什么? Will it free memory ahead p1[5]? 它会在p1 [5]之前释放内存吗? Is it safe to use memory ahead p1[5](ie p1[6], p1[7] , . .) 在p1 [5]之前使用内存是否安全(即p1 [6],p1 [7],...)?

Freeing a pointer that wasn't malloc / calloc ed is undefined behavior. 释放不是malloc / calloc ed的指针是未定义的行为。 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. 某些分配器(例如glibc)有时可以检测到它,并使用free(): invalid pointer错误消息确定性地使程序崩溃,但是从技术上讲,如果执行此操作,则将失去有关程序行为的所有保证。

You cannot predict the behavior of this function, as it is undefined behavior 您无法预测此函数的行为,因为它是未定义的行为

From the reference: 从参考:

Deallocates the space previously allocated by malloc() , calloc() , aligned_alloc , (since C11) or realloc() . 取消分配先前由malloc()calloc()aligned_alloc (自C11开始)或realloc()分配的空间。

If ptr is a null pointer, the function does nothing. 如果ptr是空指针,则该函数不执行任何操作。

The behavior is undefined if the value of ptr does not equal a value returned earlier by malloc() , calloc() , realloc() , or aligned_alloc() (since C11). 如果ptr的值不等于malloc()calloc()realloc()aligned_alloc() (自C11起realloc() ,则该行为未定义。

free , C++ Reference freeC ++参考

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; 重点:在这种情况下,您对free的使用将涉及释放一个指针,而该指针不是通过使用任何这些函数获得的; it was obtained by transforming the pointer that was obtained from malloc , and thus is not valid. 它是通过转换从malloc获得的指针而获得的,因此无效。

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. 所以不要这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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