malloc的/免费的.可以从释放的内存中读取 [英] malloc / free. can read from freed memory

查看:52
本文介绍了malloc的/免费的.可以从释放的内存中读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我如何分配内存

char *convertToPostfix(char **infixExpr)
{
    char *postfixExpr = (char *) malloc(strlen(*infixExpr) * sizeof(char) * 2);
    ...
    return postfixExpr;
}

这是我使用此内存的方式:

Here how i use this memory:

char *subexpr = convertToPostfix(infixExpr);
free(subexpr);
while (*subexpr) 
    postfixExpr[i++]=*subexpr++;

为什么在 free(subexpr); 之后,该程序仍能正常工作?我的意思是为什么释放后可以在其中迭代?

Why does this program work normally after free(subexpr); I mean why is it possible to iterate in while after freeing?

当函数返回一些在另一个上下文中释放的内存时,我是否以这种方式正确地工作了?

And am i doing everything right working in such way, when function returns some memory, which is freed in another context?

推荐答案

您的程序表现出不确定的行为.简而言之,任何事情都可能发生,包括您的程序似乎可以正常工作.

Your program exhibits undefined behaviour. In short anything can happen, including your program appearing to work.

在调用 free 之后,malloc/free的实现并不立即将内存块返回到底层操作系统是很常见的.出于性能原因执行此操作.通过返回指向刚释放的块的指针,然后重新使用它,可以最有效地处理对 malloc 的下一次调用.此时,在您的代码中,将有两个指针指向相同的内存块,谁知道接下来会发生什么.

It's quite common that implementations of malloc/free do not return memory blocks to the underlying OS immediately after you call free. This is done for performance reasons. The next call to malloc may well be most efficiently be handled by returning a pointer to the block that you just freed and therefore re-using it. At this point, in your code, there would be two pointers referring to the same block of memory and who knows what would happen next.

这篇关于malloc的/免费的.可以从释放的内存中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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