Cygwin malloc overrides another memory in heap
I have a strange error when try to malloc some memory. I've a pointer to a struct which is "malloced" and I want another struct. So I call malloc again and the pointer what malloc give back is point an empty space - so far it's ok. Then I memset the allocated area and the memset overrides another variable which is still in use. 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. The code:
data_开发者_Go百科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. processor is 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. Thanks all the advice!
If you need to set the newly allocated memory to 0 - use 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. You are allocating length
bytes. If you want an array of length
data_t
's, then you need to allocate sizeof(data_t)*length
bytes.
A better solution would be to use calloc
, as @littleadv suggests. That function takes separate arguments for number_of_items, and sizeof_item, so it's harder to get wrong.
精彩评论