在C/C++
如果使用了如果用free
分配了一块大小为x bytes
的空间的话, 据说那块空间其实不止x bytes
, 还会有多出的一部分用来保存分配空间的大小等信息, 这也是为什么free
的时候只需要传一个指针进去进行了, 我想知道的是, 那如果free
的时候我不传起点这个头指针进去, 而是把空间中任意位置的某个指针传进去, 这样的话会发生什么呢?
伊谢尔伦2017-04-17 14:27:44
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...
高洛峰2017-04-17 14:27:44
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
怪我咯2017-04-17 14:27:44
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;
}