segmentation fault

D

dentzigui

Hello, I hope to be clear. Forgive my english and forgive me if this
question is trivial.

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

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

thanx.
 
B

Bill Pursell

dentzigui said:
Hello, I hope to be clear. Forgive my english and forgive me if this
question is trivial.

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

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

At the time you make this call, last probably doesn't point to a valid
memory location. Here is a piece of code that does what you want
in 2 different ways. Understanding the differences will help.

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

struct data {
struct data *next;
char *item;
};

void
print_list(struct data *list)
{
printf("%s\n", list->item);
if (list->next != NULL)
print_list(list->next);
}

void *
initialize_entry(char *item)
{
struct data * ret;
ret = malloc(sizeof *ret);
if (ret == NULL) {
perror(NULL);
exit(EXIT_FAILURE);
}
ret->item = item;
ret->next = NULL;

return ret;
}

int
main(void)
{
struct data head_array[1];
struct data *head_ptr;

head_ptr = initialize_entry("First item in the ptr list");
head_ptr->next = initialize_entry("End of ptr list");

head_array->item = "First item in the array.";
head_array->next = initialize_entry("End of array list");

print_list(head_array);
print_list(head_ptr);

return EXIT_SUCCESS;
}
 

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,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top