C 分段错误11:10
我在解决一个问题上有问题。我得到继续分段错误:11错误,而我尝试这段代码。每次我修改代码时,错误就会弹出,我不知道缺陷在哪里,所以如果有人看到缺陷,我会非常高兴 我先谢谢你C 分段错误11:10,c,C,我在解决一个问题上有问题。我得到继续分段错误:11错误,而我尝试这段代码。每次我修改代码时,错误就会弹出,我不知道缺陷在哪里,所以如果有人看到缺陷,我会非常高兴 我先谢谢你 #include <stdio.h> #include <string.h> #include <stdlib.h> #include "dbg.h" typedef struct node{ char *data; struct node *next; } node_t;
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "dbg.h"
typedef struct node{
char *data;
struct node *next;
} node_t;
node_t **push(node_t **head, char *data){
node_t *new_node;
new_node = malloc(sizeof(node_t));
new_node->data = data;
new_node->next = *head;
*head = new_node;
free(new_node);
return head;
}
int main(int argc, char *argv[])
{
node_t **head;
char *data = "hoi";
char *data2 = "hallo";
head = malloc(20 * sizeof(node_t));
head = push(head, data);
head = push(head, data2);
printf("%s\n",(*head)[1].data);
free(head);
return 0;
}
#包括
#包括
#包括
#包括“dbg.h”
类型定义结构节点{
字符*数据;
结构节点*下一步;
}节点t;
节点**推送(节点**头,字符*数据){
node_t*新节点;
新节点=malloc(sizeof(node_t));
新建_节点->数据=数据;
新建_节点->下一步=*头部;
*head=新的_节点;
空闲(新的_节点);
回流头;
}
int main(int argc,char*argv[])
{
节点**头;
char*data=“hoi”;
char*data2=“你好”;
头部=malloc(20*sizeof(node_t));
头部=推动(头部,数据);
头部=推压(头部,数据2);
printf(“%s\n”,(*head)[1]。数据);
自由(头);
返回0;
}
缺陷:
- 您的
push()。这是分割错误的良好基础
是指向指针的指针,但被分配了head
调用的结果,该调用似乎指示它应该是指向节点的指针malloc()
- 您的设计令人困惑:您想在
或push()
中分配内存吗。当然,两者都不是一个好的选择main()
- 您使用非常量指针指向常量字符串。这是危险的。通过这些指针写入常量字符串也可能导致分段错误
#include <stdio.h>
#include <stdlib.h>
struct node {
const char *data;
struct node *next;
};
static struct node *push(struct node *head, const char *data) {
struct node *node;
node = malloc(sizeof *node);
node->data = data;
node->next = head;
return node;
}
int main(int argc, char *argv[])
{
struct node *head = NULL;
const char *data = "hoi";
const char *data2 = "hallo";
head = push(head, data);
head = push(head, data2);
struct node *node = head;
while (node) {
printf("%s\n", node->data);
node = node->next;
}
return 0;
}
#包括
#包括
结构节点{
常量字符*数据;
结构节点*下一步;
};
静态结构节点*推送(结构节点*头,常量字符*数据){
结构节点*节点;
node=malloc(sizeof*node);
节点->数据=数据;
节点->下一步=头部;
返回节点;
}
int main(int argc,char*argv[])
{
结构节点*head=NULL;
const char*data=“hoi”;
const char*data2=“你好”;
头部=推动(头部,数据);
头部=推压(头部,数据2);
结构节点*节点=头部;
while(节点){
printf(“%s\n”,节点->数据);
节点=节点->下一步;
}
返回0;
}
请注意,我实现了一个后进先出结构,aka。堆栈,因为push()
函数通常应用于堆栈
对您来说,合乎逻辑的下一步是实现
pop()
函数。通常,我建议pop()
释放节点并返回数据。这将为您的API提供一个很好的对称性。您了解SEGFULT是由什么引起的吗?这个问题一天会被问10次,答案几乎完全一样。你可能想读一下:head=malloc(20*sizeof(node_t))代码>看起来不正确!!使用调试器!这一切都应该是显而易见的。因此,head
指向new_node->next=*head之后的位置
?整体设计很奇怪:不应该使用指向节点的指针,而应该使用指向节点的指针。另外,在push
中释放new_节点
是完全错误的,你刚刚分配了它,你仍然需要它,那么你为什么要释放它?我什么时候需要释放新的_节点,因为当我不释放它时,我会正确地丢失内存?@John John,你在不再需要它时释放它。当你不再需要它时,由你决定。@JohnJohn一旦你用完它,你需要释放它,也就是说,一旦整个链表不再需要了。你在这里所做的就像买了一个冰淇淋,扔掉,然后试着吃它。