指针增加时"free"如何工作 [英] how 'free' works when pointer is incremented

查看:45
本文介绍了指针增加时"free"如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当调用malloc时,大小存储在分配的块附近,以便free知道要释放的空间,等等( http://c-faq.com/malloc/freesize.html ).

When malloc is called, the size is stored adjacent to the allocated block so that free will know how much to free etc ( http://c-faq.com/malloc/freesize.html ).

我的问题是,说我们已经动态分配了内存,然后在代码中我们增加了指针

My question is, Say we have dynamically allocated memory and later in the code we increment the pointer

 pointer++

然后,如果我打电话给

free(pointer) 

实际上释放了哪些内存.

what memory does actually get freed up.

是从指针"所指向的当前地址开始还是从其已分配的基地址开始分配的字节数.

Is it number of allocated bytes starting from the current address pointed by 'pointer' or from the base address to which it has been allocated.

推荐答案

您需要free()与从malloc()收到的指针相同.递增,更改或更改它是不确定的行为,通常是分段错误.

You need to free() the same pointer as you received from malloc(). Incrementing, altering or changing it is undefined behaviour, that is usually a segmentation fault.

考虑一下您从图书馆以书本形式收到的指针.您回家阅读.然后,您删除首页和书籍的背面,然后将其交给图书管理员.他会接受还是现在遇到严重的麻烦? ;-)

Think of the pointer you receive as a book from a library. You get home and read it. Afterwards you remove the front page and the book's back and hand it back to the librarian. Will he accept it or are you in serious trouble now? ;-)

这篇关于指针增加时"free"如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆