-1

I'm having a trouble while working on a homework. I am preparing a little project about linked lists. I wrote a program which shows me an error message about segmentation fault. I've no Idea , what does this stuff mean and what have I to do. I'm looking forward to recieving some solution from you guys here is the code

‪#‎include‬ <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Data{
int numero;
char *prenom;
float taille;
}donnees;
typedef struct list linked_list;
struct list{
donnees *data;
linked_list *next;
};
int main(){
int taille,i;
linked_list *tete,*ptr,*tete1;
tete=ptr=NULL;
printf("\nentrer le nombre des etudiants a introduire dans la liste :   ");
scanf("%d",&taille);
for(i=0;i<taille;i++){
ptr=(linked_list*)malloc(sizeof(linked_list));
printf("\nentrer le numero de l'etudiant :");
scanf("%d",&(ptr->data->numero));
printf("\nentrer le nom de l'etudiant :");
scanf("%s",(ptr->data->prenom));
printf("\nentrer le numero de l'etudiant :");
scanf("%f",&ptr->data->taille);
ptr->next=NULL;
if(tete==NULL)tete=ptr;
else{
ptr->next=tete;
tete=ptr;
}
printf("votre liste s'ecrit sous la forme :\n[tete]->");
ptr=tete;
while(ptr!=NULL){
printf("[ %d - %s -%f ]->",ptr->data->numero,ptr->data->prenom,ptr-  >data->taille);
}
printf("NULL\n");
}
return 0;
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

2 Answers2

3

I do not understand the language (used in variable naming and print statements), but it seems

 scanf("%d",&(ptr->data->numero));

is the problem. You need to allocate memory to ptr->data before dereferencing it.

To explain, data is also a pointer. You need to allocate memory [malloc()] to it before using it, just like you did for ptr.

same case is applicable for

scanf("%s",(ptr->data->prenom));

here, you need to allocate both data and prenom before using.

Also, please do not cast the return value of malloc() and family in C.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0
scanf("%d",&(ptr->data->numero));

You never allocated memory for data.

scanf("%s",(ptr->data->prenom)); 

You never allocated memory for prenom.

Use malloc as you did for ptr to allocate memory for these objects.

ouah
  • 142,963
  • 15
  • 272
  • 331