Home  >  Q&A  >  body text

C/C++语言中关于free的问题

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

大家讲道理大家讲道理2713 days ago506

reply all(3)I'll reply

  • 伊谢尔伦

    伊谢尔伦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...

    reply
    0
  • 高洛峰

    高洛峰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

    reply
    0
  • 怪我咯

    怪我咯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;
    }

    reply
    0
  • Cancelreply