strange Segmentation fault in C
int * mymalloc(int *array, int size){
//PRINTS THE TIMES MYMALLOC IS CALLED. JUST FOR TESTING;
printf("~~~~~~~~~~~~~~~TIME(S) MYMALLOC WAS CALLED:~~~~~~~~~~~~~~~ %d\n", i++);
//checks
if(size<1){
printf("SIZE NOT VALID\n");
return (int *) 0;
}
printf("MEMORY FREE JUST WHE开发者_JAVA技巧N MYMALLOC() IS CALLED: %d\n", (*((BLOCK *)array[0])).size);
BLOCK currentHeader = (*((BLOCK *)array[0]));
do{
printf("CURRENT HEADER STATUS: %d\n", currentHeader.status);
if(currentHeader.status == 0){
printf("ok\n");
if(currentHeader.size >= size){
currentHeader.status = 1;
if(currentHeader.size - size < sizeof(currentHeader))
return &array[currentHeader.data];
else{
BLOCK nextHeader;
array[size + currentHeader.data] = (int)&nextHeader;
if(currentHeader.nextb !=0){
(*currentHeader.nextb).previousb = &nextHeader;
nextHeader.nextb = currentHeader.nextb;
}
currentHeader.nextb = &nextHeader;
nextHeader.previousb = ¤tHeader;
nextHeader.size = currentHeader.size - size - sizeof(nextHeader);//here?
nextHeader.data = currentHeader.data + size + sizeof(nextHeader); //here?
printf("NEXT HEADER DATA: %d\n", nextHeader.data );
nextHeader.status = 0;
currentHeader.size = size; //changing the currentHeader.size to the "size" given.
printf("%d\n", sizeof(currentHeader));
printf("%d\n", size + currentHeader.data);
printf("%d\n", nextHeader.size);
printf("i return\n");
return &array[currentHeader.data];
}
}
//printf("NOT ENOUGH SIZE");
}
if(currentHeader.nextb !=0){
printf("%d\n",*currentHeader.nextb);
currentHeader = *currentHeader.nextb;
}
}while (currentHeader.nextb != 0);
return (int *) 0;
//printf("%d\n", (*((BLOCK *)array[0])).status );
}
ok guys when i run this program, actually when i call this method, like this
mymalloc(testarray,50);
when i comment the line printf("ok\n");
i get a segmentation fault.
printf("ok\n");
then //printf("ok\n");
if you comment that line and it crashes, it means that your stack is corrupted. So, the crash may appear and/or disappear without any apparent reason at any "random" point (of course it's not really random, but so it may seem).
Can you generate core-dumps and/or run with valgrind and/or step-by-step debug it?
Instead of doing this "by hand". I suggest using a proper tool for this like valgrind or gprof.
精彩评论