开发者

simple linked list segmentation fault

I am new with C programming language.

I am learning C about linked list, trying to print "hello world", but I got a segmentation fault.

I am using a text editor (vi) and gcc. How can I trace the error, which part causes segmentation fault, and how to fix this?

Should I put printf in everyline? I would appreciate for any help/some suggestions

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>


typedef struct {
int variable;
} abc_create_t; 

typedef struct {
int variable;
} pdn_con_t;

typedef struct pdn_con_list_t_slot {
pdn_con_t conn;
struct pdn_con_list_t_slot *next, *prev;
} pdn_con_list_t_slot;

typedef struct {
pdn_con_list_t_slot *head, *tail;
开发者_开发知识库} pdn_con_list_t;

 typedef struct {
int variable;
pdn_con_list_t connections;
 } gprs_t;

 void send_Method(gprs_t *ue, abc_create_t *msg)
 {
//assert(ue->connections.head);
printf("IN THIS BLOCK");
  }

 int main()
 {  

gprs_t *ue = NULL;
ue->variable=1;
abc_create_t *msg = NULL;
msg->variable=1;
send_Method(ue, msg);
return 0;
  }


Buddy you haven't allocated the memory and trying to store value in it.You need to use malloc() to first allocate the memory and make structure pointer point to it and then only you can work ahead.

Declaring structure does not allocate memory for its elements.You have to do this.

int main()
{  

gprs_t *ue = NULL;
ue= (gpre_t *) malloc(sizeof(gprs_t)); 
ue->variable=1; 
//Rest of the code

}


One way to debug this is to get familiar with gdb

First enable core dumps with this command:

ulimit -c unlimited 

and compile your program with -g flag to enable debug information.

Then run the executable which will cause a core file to be placed in the same folder as the executable.

Now. start gdb using

gdb ./program core

gdb should now print out a message about the error and the exact location of.


If your question is about how to debug the problem, then you should use a debugger, such as GDB. First, make sure you've compiled your program with debug information (make sure you invoke GCC with the -ggdb flag, and without any optimisations enabled). Then, invoke GDB with:

gdb --args ./my_prog param1 param2 ...

Then type run (or r for short) to begin execution. When the program crashes, the seg-fault info will be displayed in GDB. Type backtrace (or bt for short) to get the stack trace, i.e. which functions and line numbers you're on when the crash occurred.


Most obvious: you're assigning NULL to ue, and then dereferencing ue. This is undefined behavior; you first have to allocate memory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜