[英]segfault with linked list
I am having trouble with linked lists in C, I have only done data structures such as this in c++. 我在C中遇到链表问题,我只在c ++中完成过这样的数据结构。
Gdb is giving me a Gdb给我一个
Program received signal SIGSEGV, Segmentation fault. 0x0804a23c in addArg (base=0x1, argument=0x804e410 "is") at myshell.c:42 42 while ( (curr != NULL) && (curr->n != NULL) )
I am familiar with segmentation faults having to do with memory, however I thought I have allocated memory correctly. 我熟悉与内存有关的分段错误,但是我认为我已正确分配了内存。 What am I doing wrong? 我究竟做错了什么?
addArg is being called as addArg(currentCmd->args, lexeme);
addArg被称为addArg(currentCmd->args, lexeme);
and currentCmd is a pointer to a node struct 而currentCmd是指向节点结构的指针
struct lnode {
char *x;
struct lnode *n;
};
struct node
{
char *command;
struct lnode *args;
int input;
int output;
int error;
char *in;
char *out;
char *err;
struct node *next;
struct node *prev;
};
void addArg(struct lnode *base, char *argument)
{
struct lnode *curr = base;
//this is line 42
while ( (curr != NULL) && (curr->n != NULL) )
curr = curr->n;
curr -> n = malloc(sizeof(struct lnode));
curr = curr->n;
curr->x = strdup(argument);
curr->n = NULL;
}
struct node* createNode(char *command_, int input_, int output_, int error_, char *in_, char *out_, char *err_, struct node *prev_)
{
struct node *n;
n = malloc(sizeof (struct node));
n->command = strdup(command_);
n->prev = prev_;
n->next = NULL;
n->input = input_;
n->output = output_;
n->error = error_;
n->in = in_;
n->out = out_;
n->err = err_;
n->args=malloc(sizeof(struct lnode));
return n;
}
It looks like currentCmd->args
is an invalid pointer. 看起来currentCmd->args
是无效的指针。 Perhaps a pointer to free()
d memory. 也许是指向free()
d内存的指针。 Or an uninitialized pointer, or a pointer to a local variable that's gone out of scope (though these latter two don't appear to be the case here). 或未初始化的指针,或指向超出范围的局部变量的指针(尽管后两个在这里似乎不是这种情况)。
Or perhaps you've accidentally overwritten out-of-bounds memory somewhere else in your program. 也许您不小心覆盖了程序中其他地方的越界内存。 Pointer issues aren't always at the point of failure; 指针问题并不总是会出现故障。 sometimes they're in earlier code, unrelated code even. 有时他们使用的是早期代码,甚至不相关的代码。
我通过将lnode *args
为lnode args
并对内存管理进行了必要的更改来解决了这个问题。
我从您的gdb输出中看到的是while ( (curr != NULL) && (curr->n != NULL) )
是,如果curr == NULL您仍在尝试访问curr-> n进行比较,因此您应该更改该条件以仅比较curr,并且仅在curr不为null时处理curr-> n,如果curr-> n == NULL,则可能会立即中断子句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.