在C/C++如果使用了如果用free分配了一块大小为x bytes的空间的话, 据说那块空间其实不止x bytes, 还会有多出的一部分用来保存分配空间的大小等信息, 这也是为什么free的时候只需要传一个指针进去进行了, 我想知道的是, 那如果free的时候我不传起点这个头指针进去, 而是把空间中任意位置的某个指针传进去, 这样的话会发生什么呢?
C/C++
free
x bytes
光阴似箭催人老,日月如移越少年。
Is this what the question means?
#include <stdio.h> #include <stdlib.h> int main() { int* ptr = (int*)malloc(3 * sizeof(int)); printf("%x\n", ptr); printf("%x", ptr + 1); free(ptr + 1); return 0; }
will cause undefined behavior. http://www.cplusplus.com/refe...
An error will be reportedpointer being freed was not allocated. If you are not allowed to do such illegal things, the program will not be so stupid
pointer being freed was not allocated
It will explode... The specific method of explosion depends on the implementation of the operating system. Anyway, it will explode. If LZ is interested, you can go and run it under your operating system:
#include <cstdio> using namespace std; struct zz{ zz(){puts("BEGIN");} ~zz(){puts("END");} }; int main() { zz *a=new zz[5]; delete [](a+1); return 0; }
Is this what the question means?
will cause undefined behavior. http://www.cplusplus.com/refe...
An error will be reported
pointer being freed was not allocated
. If you are not allowed to do such illegal things, the program will not be so stupidIt will explode... The specific method of explosion depends on the implementation of the operating system. Anyway, it will explode. If LZ is interested, you can go and run it under your operating system: