我正試圖爲我的C程序中的自定義堆棧分配一些動態內存。但是,我收到錯誤0xC0000005:在malloc調用期間寫入位置0x00000014訪問衝突。嘗試分配內存使用malloc自定義結構時出錯
這裏是我的結構定義和我的函數調用malloc:
#include <stdio.h>
#include <stdlib.h>
#define EMPTY -1;
typedef enum boolean_tag { TRUE, FALSE } Boolean;
typedef enum direction_tag { ACROSS, DOWN } AnswerDirection; /*The direction of an answer in the crossword*/
typedef struct answer_tag {
/*A single 'Answer' is a single node making up a linked list*/
int answerNumber;
AnswerDirection direction;
char *answerString; /*The answer's value in chars*/
struct answer_tag *nextAnswer; /*Points to the next answer in the linked list*/
} Answer;
typedef struct space_tag {
/*A single space inside of a board*/
int numberOfCurrentAnswers; /*How many Answers currently cross through the space*/
char value;
int x;
int y;
struct space_tag *behindSpace;
struct space_tag *nextSpace;
} Space;
void InitAnswers(Answer *);
Space *InitCrossword();
Space *InitSpace();
void ProgramClosingCleaning(Space *);
main(){
Space *board;
board = InitCrossword();
ProgramClosingCleaning(board);
}
void InitAnswers(Answer *answerKey){
}
Space *InitCrossword(){
int xLimit, yLimit; /*Limits set*/
int xTraverse, yTraverse; /*Coordinate variables to use in traversing*/
Space *currentSpace = NULL;
Space *nextSpace;
printf("Please enter the size of the board: x y\n");
scanf("%d %d", &xLimit, &yLimit);
for (xTraverse = 0; xTraverse < xLimit; xTraverse++){
for (yTraverse = 0; yTraverse < yLimit; yTraverse++){
nextSpace = InitSpace();
nextSpace->x = xTraverse;
nextSpace->y = yTraverse;
nextSpace->numberOfCurrentAnswers = 0;
nextSpace->value = EMPTY;
nextSpace->behindSpace = currentSpace;
currentSpace->nextSpace = nextSpace;
currentSpace = nextSpace;
}
}
while (currentSpace->behindSpace != NULL)
currentSpace = currentSpace->behindSpace;
return currentSpace;
}
Space *InitSpace(){
return (Space *) malloc(sizeof(Space));
}
void ProgramClosingCleaning(Space *currentSpace){
Space *nextSpace;
while (currentSpace != NULL){
nextSpace = currentSpace->nextSpace;
free(currentSpace);
}
}
感謝您的幫助!
你能發佈一個小程序來重現這個嗎? – hmjd
看起來你的堆已經被更早的東西損壞了。另外,它似乎是你在Windows上運行(通過錯誤代碼);我不是很確定,但我認爲Windows可能對線程使用的堆棧有一些特定的要求/期望。我不確定您是否可以將線程的堆棧設置爲某個任意內存塊。 –
我發佈了一個示例程序。是的,我正在運行Windows。 – atob