使用malloc释放为char *分配的内存 [英] freeing memory allocated for char* using malloc
本文介绍了使用malloc释放为char *分配的内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我期待的输出是分段错误,但有些输出即将来临。
The output what i am expecting is a segmentation fault but some output is coming.
展开 | 选择 | Wrap | 行号
推荐答案
@dheerajjoshim
如果您有一个长度为n的字符串,则需要n + 1个字节来存储它,即另外一个用于存储它字符串终止''\ 0''字符。所以你必须这样做:
@dheerajjoshim
If you have a string of length n you need n+1 bytes to store it, i.e. one more for the string terminating ''\0'' character. So you have to do:
展开 | 选择 | Wrap | 行号
感谢您的信息Jos ...我不会得到堆栈现在跟踪错误..
Thanks for the info Jos... I wont get the stack trace error now..
展开 | 选择 | Wrap | 行号
@dheerajjoshim
这是未定义的行为;你释放了()记忆,所以它不再是你的了。它可能会在其他上下文或其他实现中抛出分段违规,或者在您运行程序时可能会出现奇怪的行为;这就是未定义行为的全部内容。
回答你的上一个问题:你不知道是否分配或释放了一块内存,即你有通过程序的控制流程来查找。
亲切的问候,
Jos
@dheerajjoshim
It''s undefined behaviour; you have freed() the memory so it isn''t yours anymore. It may throw a segmentation violation in other contexts or other implementations or it may behave strangely next to you run your program; that''s what undefined behaviour is all about.
To answer your last question: you don''t know whether or not a piece of memory is allocated or freed, i.e. you have to go through the control flow of your program to find out.
kind regards,
Jos
这篇关于使用malloc释放为char *分配的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文