I'm developing a C project , and it turns out that in a specific moment, i call calloc() function and it assigns a memory block which is already in use . How is that possible ? I've checked my memory-allocation usages and for every time i call malloc/calloc then i call free(pointer_to_the_allocated_memory) . So, it's not a memory leak issue neither a twice-freed pointer. I don't paste my code since it is for a colleage work and i haven't sent it yet. Any type of help/advice is welcomed. Thanks in advance.
It is possible that two pointers point to the same place.
p1 = malloc(sizeof(int));
/* ... */
p2 = p1;
/* ... */
free(p1);
/* ... */
p3 = malloc(sizeof(int)); /* may allocate the block already used by p2 */
Note that it is often not that obvious. It may happen via pointer arithmetics (i.e. p2++
), or different parts of this may be done in different functions.
Another possibility is that you free a pointer without noticing it:
p1 = malloc(sizeof(int));
foo(p1); /* this function calls free(p1) */
p2 = malloc(sizeof(int)); /* may allocate the block already used by p1 */