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.