gpt4 book ai didi

c - 为什么 malloc 多次分配失败?

转载 作者:太空宇宙 更新时间:2023-11-04 06:25:29 24 4
gpt4 key购买 nike

我编写了一个简单的源代码。它包含一个队列和一些队列需要的功能,但由于某种原因 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 结构,使 valuechar [SOME_SIZE],要么使用 strdup() 而不是 strcpy(),实际为可怜的东西分配一些内存。

n->value = strdup(instruction);

关于c - 为什么 malloc 多次分配失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27527948/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com