1
#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) !

Anis_Stack
  • 3,306
  • 4
  • 30
  • 53
  • 4
    You've allocated space for `cf`, but do you have any reason to suppose that its `struct a1` pointer, `a1`, points to accessible memory? `cf->a1` is a meaningless value, and you shouldn't be trying to dereference it. You need an intervening `cf->a1 = malloc(sizeof(struct a1));`. – Joshua Taylor Feb 25 '14 at 16:29

3 Answers3

3

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);

}
ArtoAle
  • 2,939
  • 1
  • 25
  • 48
0

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);

}
WileTheCoyot
  • 513
  • 1
  • 5
  • 20
  • you don't cast `malloc` in C - [Do I cast the result of malloc?](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – crashmstr Feb 25 '14 at 17:05
  • @crashmstr if you use gcc you will get a syntax error if you don't cast – WileTheCoyot Feb 25 '14 at 18:41
  • You should not get a syntax error with a C compiler, C++ on the other hand, yes, you would need to. Question is tagged C though. – crashmstr Feb 25 '14 at 18:46
0

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));

Sunil Bojanapally
  • 12,528
  • 4
  • 33
  • 46