Maison  >  Questions et réponses  >  le corps du texte

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

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

大家讲道理大家讲道理2713 Il y a quelques jours510

répondre à tous(3)je répondrai

  • 伊谢尔伦

    伊谢尔伦2017-04-17 14:27:44

    题主是这个意思吗?

    #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;
    }
    
    

    会导致未定义行为。http://www.cplusplus.com/refe...

    répondre
    0
  • 高洛峰

    高洛峰2017-04-17 14:27:44

    会报错pointer being freed was not allocated,不让你干这种非法的事,程序不会那么傻的

    répondre
    0
  • 怪我咯

    怪我咯2017-04-17 14:27:44

    会炸掉……具体的炸法取决于操作系统的实现,反正都是炸,LZ有兴趣的话可以去你的操作系统下跑一跑:

    #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;
    }

    répondre
    0
  • Annulerrépondre