[英]Error while trying to allocate memory using malloc for custom struct
我試圖在我的c程序中為自定義堆棧分配一些動態內存。 但是,我在malloc調用期間收到錯誤0xC0000005:訪問沖突寫入位置0x00000014。
這是我的struct定義和調用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);
}
}
謝謝你的幫助!
我看到發布的代碼存在兩個問題(編譯器應該發出警告):
Init()
和InitSpace()
隱式聲明意味着它們的返回類型為int
Init()
不返回值。 問題是InitCrossword()
函數中的這一行:
currentSpace->nextSpace = nextSpace;
在for
循環的第一次迭代中for
currentSpace
為NULL。
我非常確定您使用的語法會創建類型為space_tag
的結構,而Space
實際上是一個變量(請參閱http://www.cplusplus.com/doc/tutorial/structures/ )。
試試這段代碼:
#include <stdio.h>
#include <stdlib.h>
typedef struct Space {
int numberOfCurrentAnswers;
char value;
int x;
int y;
struct Space *lastSpace;
struct Space *nextSpace;
};
main(){
struct Space *space;
space = Init();
}
Space *Init(){
struct Space *nextSpace;
nextSpace = InitSpace();
}
Space *InitSpace(){
return (Space *) malloc(sizeof(Space));
}
根據發布的示例代碼進行編輯
您缺少Init();
的返回函數Init();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.