segmentation fault

D

dentzigui

Hello,

struct _data {
struct _data *next;
char *item; };
....
srtuct _data *last;

last->next = (struct _data *) malloc (sizeof (struct _data)); ----> why
this causes a segmentaion fault?
 
I

Ian Collins

dentzigui said:
Hello,

struct _data {
struct _data *next;
char *item; };
....
srtuct _data *last;

last->next = (struct _data *) malloc (sizeof (struct _data)); ----> why
this causes a segmentaion fault?
You haven't assigned anything to last. Also don't cast the return value
of malloc.
 
C

CBFalconer

dentzigui said:
struct _data {
struct _data *next;
char *item; };
...
srtuct _data *last;

last->next = (struct _data *) malloc (sizeof (struct _data));
----> why this causes a segmentaion fault?

Possibly because you have invoked undefined behaviour by using an
identifier that begins with _. Possibly because you have
suppressed an error by erroneously casting the result of malloc.
Possibly because you have defined last to point to an undefined
thing. Possibly because last is uninitialized, and points
nowhere. Congratulations on the number of errors you have managed
to cramp into 5 lines.
 
D

Default User

colitas said:
struct _data *last = (struct _data *)malloc(sizeof(struct _data));

Don't top-post. Your reply belongs following or interspersed with
trimmed quotes.

Also, your "solution" needlessly casts the return from malloc(), which
can hide a dangerous condition. See the newsgroup FAQ for details.



Brian
 
A

Andrew Poelstra

struct _data *last = (struct _data *)malloc(sizeof(struct _data));

Do not toppost. Google, the Urban Dictionary, and any Usenet archive
will tell you what that means, if you haven't figured it out already.

Then, don't offer bad advice. The original code doesn't compile
because of at least one syntax error I see, and almost certainly
had other problems besides. The proper form of malloc is:

p = malloc(n * sizeof*p);

Your choice of spacing.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top