简体   繁体   English

malloc'd内存和sigsegv

[英]malloc'd memory and sigsegv

help me in understanding the malloc behaviour.. my code is as follows:: 帮助我理解malloc行为..我的代码如下::

    int main()
    {   
    int *ptr=NULL;
    ptr=(int *)malloc(1);
    //check for malloc
    *ptr=1000;

    printf("address of ptr is %p and value of ptr is %d\n",ptr,*ptr);
    return 0;
    }

the above program works fine(runs without error)...how?? 上面的程序工作正常(运行没有错误)......怎么样? as I have supplied a value of 1000 in 1 byte only!! 因为我只用1字节提供了1000的值!!

Am I overwriting the next memory addresss in heap? 我是否覆盖了堆中的下一个内存地址? if yes, then why not sigsgev is there? 如果是的话,为什么不是sigsgev?

Many implementations of malloc will allocate at a certain "resolution" for efficiency. malloc许多实现都会以一定的“分辨率”进行分配以提高效率。

That means that, even though you asked for one byte, you may well have gotten 16 or 32. 这意味着,即使你要求一个字节,你可能已经得到16或32。

However, it's not something you can rely on since it's undefined behaviour. 但是,由于它是不确定的行为,因此您不能依靠它。

Undefined behaviour means that anything can happen, including the whole thing working despite the problematic code :-) 未定义的行为意味着任何事情都可能发生,包括尽管有问题的代码整个工作:-)

Using a debug heap you will definitely get a crash or some other notification when you freed the memory (but you didn't call free). 使用调试堆,当你释放内存时你肯定会遇到崩溃或其他通知(但你没有免费调用)。

Segmentation faults are for page-level access violations, and a memory page is usually on the order of 4k, so an overrun by 3 bytes isn't likely to be detected until some finer grained check detects it or some other part of your code crashes because you overwrote some memory with 'garbage' 分段错误用于页面级访问冲突,并且内存页通常大约为4k,因此在一些细粒度检查检测到它或代码的其他部分崩溃之前,不太可能检测到超出3个字节的溢出因为你用“垃圾”覆盖了一些记忆

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM