h*****g 发帖数: 312 | 1 if free an obj initiated on stack, what happened? what about on heap | c***2 发帖数: 838 | 2 stack: double free? (it's supposed to be managed by OS)
heap: normal use, you always need to free it since it's allocated by you. | t****t 发帖数: 387 | | p******x 发帖数: 691 | 4
stack frames的管理是由编译器决定
管理stack 的指令由编译器插入你程序的二进制代码中
malloc() and free()都是针对heap的,不是针对stack.
double free buffers in stack?
可能会有出错信息,这取决于你的heap管理。
如果你用free(buf1), buf1不在heap范围,会出错。
对于heap 的buffer, 每个buffer块也是按照大小分别管理的
每个buffer块都有meta data指出该块范围等信息。
如果用C/C++.需要
如果是用java,python等,由VM或者interpreter负责管理heap.
【在 c***2 的大作中提到】![](/moin_static193/solenoid/img/up.png) : stack: double free? (it's supposed to be managed by OS) : heap: normal use, you always need to free it since it's allocated by you.
| f*****y 发帖数: 444 | 5 the heap one is easy. if you free an obj on stack, when the stack pop its
content, it will de-reference a piece of memory that stack no longer owns (
an dangling pointer), so the result is undefined. | c*********t 发帖数: 2921 | 6 写了一个很简单的程序,在linux下试了试,是segmentation fault, 程序退出。并且用
valgrind verify了一下,是同样的结果。
#include
// del_stack_variable.c
// this program tries to delete a variable in a function
//
int main()
{
int j=10;
printf("the addr of j =%p, j = %d\n", &j, j);
printf("delete j \n");
free(&j); //this will cause segmentation fault
printf("after that\n");
printf("the addr of j =%p, j = %d\n", &j, j);
return 0;
}
gcc -o del_stack del_stack_variable.c
$ ./del_stack
the addr of j =0xbff6c4b0, j = 10
delete j
Segmentation fault
$ valgrind ./del_stack
the addr of j =0xbe9374e0, j = 10
delete j
==27295== Invalid free() / delete / delete[]
==27295==
==27295== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 12 from 1)
==27295== malloc/free: in use at exit: 0 bytes in 0 blocks.
==27295== malloc/free: 0 allocs, 1 frees, 0 bytes allocated.
==27295== For counts of detected errors, rerun with: -v
==27295== All heap blocks were freed -- no leaks are possible.
【在 h*****g 的大作中提到】![](/moin_static193/solenoid/img/up.png) : if free an obj initiated on stack, what happened? what about on heap
|
|