Anis_Stack
Anis_Stack

Reputation: 3452

why Segmentation fault occurs in the following C code

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

struct a1 {
    int value ;
};

struct cf {
   struct a1 *a1;
   int val;
};

main(){

   struct cf *cf = malloc(sizeof(struct cf));

   cf->a1->value = 45;
   printf("cf->a1->value = %d \n",cf->a1->value);

}

when I am tying to execute this C code I'm getting a Segmentation fault (core dumped) !

Upvotes: 1

Views: 85

Answers (3)

WileTheCoyot
WileTheCoyot

Reputation: 523

You get the segmentation fault because you haven't allocated memory for a1. You should also cast the malloc from void* to struct cf* and declare the main function as int main() and return 0 if everything goes well. Here is a solution to your problem:

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

struct a1 {
    int value ;
};

struct cf {
   struct a1 *a1;
   int val;
};

int main(){

   struct cf *cf = (struct cf*)malloc(sizeof(struct cf));
   cf->a1=(struct a1*)malloc(sizeof(struct a1));

   cf->a1->value = 45;
   printf("cf->a1->value = %d \n",cf->a1->value);

}

Upvotes: 0

Sunil Bojanapally
Sunil Bojanapally

Reputation: 12658

malloc(sizeof(struct cf)); here you are allocating memory for struct cf which has members as a pointer a1 & val. Pointer a1 points to struct type a1 which has member value in it. But the malloc() allocates only memory for pointer but it doesn't allocate memory for member which it has i.e value. There you are trying to write 45 to a unknown memory.

Allocate memory for struct a1 too as, cf->a1 = malloc(sizeof(struct a1));

Upvotes: 0

ArtoAle
ArtoAle

Reputation: 2977

The reason is that you're allocating the required memory for cf but not for a1. You have to do something like

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

struct a1 {
    int value ;
};

struct cf {
   struct a1 *a1;
   int val;
};

main(){

   struct cf *cf = malloc(sizeof(struct cf));
   cf->a1 = malloc(sizeof(struct a1));
   cf->a1->value = 45;
   printf("cf->a1->value = %d \n",cf->a1->value);

}

Upvotes: 3

Related Questions