检测到glibc – 双重免费或腐败
发布时间:2020-12-16 09:29:41 所属栏目:百科 来源:网络整理
导读:这可能有点长,所以我道歉. 考虑以下代码(我从中留下了一些不相关的部分).此代码接收指向结构(BoardP theBoard)的指针,x y coords和value. 目标是将值放在结构中找到的2D数组中. 如果coords超出范围,我必须增加表的大小,将旧数据复制到新数据并将值放在其位置
这可能有点长,所以我道歉.
考虑以下代码(我从中留下了一些不相关的部分).此代码接收指向结构(BoardP theBoard)的指针,x& y coords和value. 目标是将值放在结构中找到的2D数组中. 如果coords超出范围,我必须增加表的大小,将旧数据复制到新数据并将值放在其位置. 以及此代码在第一次调用时工作,但在第二次调用中它会崩溃并写入: *** glibc detected *** ./b: double free or corruption (top): 0x092ae138 *** 我找不到答案,希望你会帮忙. BoardP p = CreateNewBoard(10,10); PutBoardSquare(p,10,5,'X'); PutBoardSquare(p,'O'); Boolean PutBoardSquare(BoardP theBoard,int X,int Y,char val) { if (inBounds(X,Y,theBoard->_rows,theBoard->_cols)) { theBoard->_board[X * theBoard->_cols + Y] = val; return TRUE; } else { int newRows = (X>=theBoard->_rows) ? (2*X) : theBoard->_rows; int newCols = (Y>=theBoard->_cols) ? (2*Y) : theBoard->_cols; BoardP newBoard = CreateNewBoard(newCols,newRows); //this creates a new Board with the new dimensions if (newBoard == NULL) { //ReportError(MEM_OUT); return FALSE; } else { copyData(theBoard,newBoard); freeBoardArray(&theBoard->_board[0]); //free old array theBoard->_board = newBoard->_board; //old array point to new array FreeBoard(newBoard); //free the temp copy THIS CAUSES THE PROBLEM PutBoardSquare(theBoard,X,val);//recursion,will be in bounds now return TRUE; } } } 这些是免费功能: void FreeBoard(BoardP board) { if (board != NULL) { printf("FREE 1n"); //free the board array: if (board->_board != NULL) { printf("FREE 2n"); freeBoardArray(&board->_board[0]); printf("FREE 3n"); } free(board); } } static void freeBoardArray(char * arrP) { free(arrP); //**PROGRAM CRASH HERE** } 这就是我创建一个新板的方式: BoardP CreateNewBoard(int width,int high) { BoardP board = (BoardP) malloc(sizeof(Board)); if (board != NULL) { board->_board = allocateBoardArray(high,width); if ( board->_board == NULL) { FreeBoard(board); //TODO make file ReportError(MEM_OUT); return NULL; } initializeBoard(board,high,width,X_SIGN,SPACE); return board; } else { FreeBoard(board); //TODO make file ReportError(MEM_OUT); return NULL; } } static char* allocateBoardArray(int row,int col) { char* newBoard = (char*) malloc(row * col * sizeof(char)); if (newBoard == NULL) { return NULL; } return newBoard; } 这是BoardP: typedef struct Board* BoardP; 解决方法
您必须释放已分配的内存,并且不再想要保留引用.
从你的代码我可以看到以下行. theBoard->_board = newBoard->_board; 现在,您保持对已分配指针的引用,然后释放相同的指针本身. 示例代码: char *foo() { char *ref1; char *ref2; ref1 = malloc(256); ref2=ref1;// Holding reference to a pointer in another pointer strcpy(ref1,"stackoverflow"); printf("%s %s",ref1,ref2); // This prints stackoverflow twice free(ref1); // This is valid but you can access ref2 or ref1 after this point return ref2; /// This will cause problems } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |