由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 问道C内存的题?
相关主题
问一个C的简单问题Google上收索leetcode的题,90%都是国人的blog链接
Unix/Linux下的C++ coding 跟Windows下到底有多大不同?给大家看几道C 小程序
求指点一下我写的程序哪部分是C++ syntax一道小题
C语言高手帮我看看下面代码,哪里错了啊,谢了关于判断stack grows up or down那道题
白板代码,支持O(1)时间GetMin的stack一个面试题目
Arista Networks面经2问个Print null的问题
c++ 问题Linux context switch 高通 面试题。??
请教一个指针的面试题算法:按照字典序求第k个排列数
相关话题的讨论汇总
话题: stack话题: 27295话题: heap话题: free话题: delete
进入JobHunting版参与讨论
1 (共1页)
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
3
前一个是undefined behavior
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 的大作中提到】
: 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 的大作中提到】
: if free an obj initiated on stack, what happened? what about on heap
1 (共1页)
进入JobHunting版参与讨论
相关主题
算法:按照字典序求第k个排列数白板代码,支持O(1)时间GetMin的stack
问个C++题Arista Networks面经2
Two C++ questions from Bloomberg on-sitec++ 问题
C++问题3请教一个指针的面试题
问一个C的简单问题Google上收索leetcode的题,90%都是国人的blog链接
Unix/Linux下的C++ coding 跟Windows下到底有多大不同?给大家看几道C 小程序
求指点一下我写的程序哪部分是C++ syntax一道小题
C语言高手帮我看看下面代码,哪里错了啊,谢了关于判断stack grows up or down那道题
相关话题的讨论汇总
话题: stack话题: 27295话题: heap话题: free话题: delete