简体   繁体   English

Cygwin malloc覆盖堆中的另一个内存

[英]Cygwin malloc overrides another memory in heap

I have a strange error when try to malloc some memory. 尝试malloc一些内存时,我有一个奇怪的错误。 I've a pointer to a struct which is "malloced" and I want another struct. 我有一个指向结构的指针,它是“malloced”,我想要另一个结构。 So I call malloc again and the pointer what malloc give back is point an empty space - so far it's ok. 所以我再次调用malloc并且malloc返回的指针指向一个空的空间 - 到目前为止它还可以。 Then I memset the allocated area and the memset overrides another variable which is still in use. 然后我memset分配的区域和memset覆盖另一个仍在使用的变量。 The first struct in the memory is in 0x1643c98 and the given pointer to the second is 0x1643bf8 but I want to malloc 200 byte. 内存中的第一个结构位于0x1643c98,第二个结构指向第二个结构是0x1643bf8,但我想要malloc 200字节。 The code: 编码:

data_t *data = get_head_data(); 
int length = data->head.length;
data_t *new_data = malloc(length); 
memset(new_data, 0x00, length); // this line override the perivously malloced data 
//some other operation

I use window xp (32 bit) and cygwin, with gcc 3.4.4. 我使用窗口xp(32位)和cygwin,使用gcc 3.4.4。 processor is intel core 2 duo. 处理器是intel core 2 duo。 Any idea whats wrong or what should be the problem? 任何想法是错的或应该是什么问题? Thanks in advance. 提前致谢。

EDIT: Sorry I was a totally wrong track. 编辑:对不起,我是一个完全错误的轨道。 There is a buggy function which is call free unexpected. 有一个错误的功能,无人值守意外。 When I call malloc later the the previous address is in the memory and I think it's a valid, but it was free()-ed. 当我稍后调用malloc时,前一个地址在内存中,我认为它是有效的,但它是免费的() - 编辑。 Thanks all the advice! 谢谢你的建议!

If you need to set the newly allocated memory to 0 - use calloc . 如果需要将新分配的内存设置为0 - 请使用calloc You're probably confusing pointers, sizes, and variables - check your code again. 您可能会混淆指针,大小和变量 - 请再次检查您的代码。

data_t *new_data = malloc(length);

Unless sizeof(data_t) is 1, that line is likely to be an error. 除非sizeof(data_t)为1,否则该行可能是错误。 You are allocating length bytes. 您正在分配length字节。 If you want an array of length data_t 's, then you need to allocate sizeof(data_t)*length bytes. 如果你想要一个length data_t的数组,那么你需要分配sizeof(data_t)*length bytes。

A better solution would be to use calloc , as @littleadv suggests. 更好的解决方案是使用calloc ,正如@littleadv建议的那样。 That function takes separate arguments for number_of_items, and sizeof_item, so it's harder to get wrong. 该函数为number_of_items和sizeof_item采用单独的参数,因此更难出错。

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

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