C: MSVC2008 Malloc and crashing program
This question might be remedial but I am having a lot of trouble with malloc. Why does my progrm crash upon freeing memory?
#include <stdlib.h>
#include <malloc.h>
int main(int argc, char *argv[]) {
int *arr[10];开发者_如何学编程
void *mem = malloc( 10 * sizeof(int) );
int i;
for(i=0;i<=9;i++) {
arr[i] = (int*) mem + i*sizeof(int);
*arr[i]= 9-i;
}
//void** ar = (void**) arr;
//medianSort(ar, cmp, 0, 9);
free(mem); //crashes here
return 0;
}
Runtime Error Message Box Reports:
Windows has triggered a breakpoint in medianSort.exe. This may be due to a corruption of the heap, which indicates a bug in medianSort.exe or any of the DLLs it has loaded. This may also be due to the user pressing F12 while medianSort.exe has focus. The output window may have more diagnostic information.
The following is is the error block from malloc.c:
#ifdef _WIN64
return HeapAlloc(_crtheap, 0, size ? size : 1);
#else /* _WIN64 */
if (__active_heap == __SYSTEM_HEAP) {
return HeapAlloc(_crtheap, 0, size ? size : 1); //crashes here
} else
if ( __active_heap == __V6_HEAP ) {
if (pvReturn = V6_HeapAlloc(size)) {
return pvReturn;
}
}
You are writing beyond allocated memory. Note that (int*) mem
is int
pointer, so adding 1 actually moves memory location by sizeof(int)
bytes. In other words, you shouldn't be doing sizeof(int)
yourself within loop, because pointer arithmetic says compiler does that for you.
精彩评论