C/C++语言中关于free的问题
大家讲道理
大家讲道理 2017-04-17 14:25:44
0
3
564

C/C++如果使用了如果用free分配了一块大小为x bytes的空间的话, 据说那块空间其实不止x bytes, 还会有多出的一部分用来保存分配空间的大小等信息, 这也是为什么free的时候只需要传一个指针进去进行了, 我想知道的是, 那如果free的时候我不传起点这个头指针进去, 而是把空间中任意位置的某个指针传进去, 这样的话会发生什么呢?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(3)
伊谢尔伦

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

刘奇

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;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template