[英]Why does malloc fail to allocate more than once?
我編寫了一個簡單的源代碼。 它包含一個隊列和隊列需要的某些功能,但由於某種原因,malloc()僅工作一次。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define QUEUE sizeof(Queue)
節點和隊列的定義,即列表的元素。
typedef struct node {
char * value;
struct node * next;
} Node;
typedef struct queue {
Node * head;
Node * tail;
} Queue;
int initialization(void ** list, int type){
int code = -1;
//create an empty list.
//if queue dynamically allocate memory and assign NULL to both properties head and tail.
return code;
}
enqueue()一次在隊列中添加一個元素。 但是由於某種原因,它只能添加一個元素,然后程序崩潰。
int enqueue(Queue * q, char * instruction){
int code = -1;
if(q != NULL){
printf("Prepare to enqueue!\n");
Node * n = NULL;
n = (Node*)malloc(sizeof(Node));
if(n != NULL){
printf("Node created!\n");
strcpy(n->value, instruction);
n->next = NULL;
//if first value
if(q->head == NULL){
q->head = n;
q->tail = n;
printf("Enqueue first Node\n");
}
else {
q->tail->next = n;
q->tail = n;
printf("Enqueue another Node\n");
}
code = 0;
printf("Node \"%s\" Enqueued\n", instruction);
}
}
return code;
}
int dequeue(Queue * q){
int code = -1;
//dequeuing code here.
return code;
}
int isEmpty(void * list, int type){
int code = 0;
//check if the list is empty
return code;
}
main()函數中的for循環永遠不會達到3
int main(int argc, char * argv[]){
Queue * queue = NULL;
initialization((void*)&queue, QUEUE);
int i = 0;
for(i = 0; i < 3; i++){
if(enqueue(queue, "some value") != 0){
printf("couldn't add more Node\n");
break;
}
}
while(!isEmpty(queue, QUEUE)){
dequeue(queue);
}
return 0;
}
初始化函數是用這種方式編寫的,因為它也應該能夠初始化堆棧(我刪除了堆棧代碼以減少源,但即使沒有它,該錯誤仍然存在)。 我還把printfs調試代碼。 而且我有足夠的內存來使此簡單代碼按應有的方式運行。
提前致謝!
運行此程序,由於出現分段錯誤而導致崩潰,正如我期望的那樣:
n = (Node*)malloc(sizeof(Node));
n
被分配,其內容未初始化且有效地隨機
if(n != NULL){
n
不是NULL,所以...
strcpy(n->value, instruction);
我們崩潰了。
看到問題了嗎? n->value
是指向無處的指針。 或者,到某個地方,但無所知 。 哪里都不好 。 我們只是將字符串轉儲到該空間中。
更改Node
結構,使其value
char [SOME_SIZE]
,或使用strdup()
而不是strcpy()
來為可憐的東西分配一些內存。
n->value = strdup(instruction);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.