malloc 之后的 memset
我有一个 Linux 产品的三行(版本)。 V1 在客户中运行良好。 V2和V3 崩溃了,修复似乎是在 malloc 调用之后调用 memset 。
关于这个话题的更深层次的解释是什么?为什么 memset 解决了这个问题?
I have three lines (version) of a linux product. V1 works fine in the customer. V2 and V3
crashed and the fix seems to be a memset call after a malloc call.
What is the deeper explanation on this topic? Why memset resolved the issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我在没有代码示例的情况下猜测是,您正在对您分配的缓冲区或结构进行操作,并假设其内容将使用某些默认值进行初始化。 Malloc 不会初始化它返还的内存,因此除非您使用 memset 或使用其他初始化,否则该内存中的值可能是任何值,因此,如果您尝试检查指针,假设它为 NULL 或int 将为零,如果不首先初始化内存,就无法做出该假设。
My guess without a code example is that you were operating on the buffer or struct you malloc'd with assumptions that its contents would be initialized with certain default values. Malloc doesn't initialize the memory it hands back, so unless you memset or use some other initialization, the values in that memory could be anything, and therefore, if you're trying to check a pointer assuming it'd be NULL or that an int will be zero, you can't make that assumption without initializing the memory first.
也许是因为有一个错误的假设,即分配的缓冲区已清零。因此,例如,如果缓冲区包含字符串并在初始化之前在某处打印,则可能会导致访问冲突。将缓冲区清零可以解决此类问题。
Maybe because there is a wrong assumtion that the allocated buffer is zeroed. So for example if the buffer contains a string and is printed somewhere before initialize, it can result in an access violation. Zeroing the buffer would fix such an issue.