-3

I'm working on a project and trying to perform a similar operation as given below, but getting segmentation fault error. I don't understand why it is giving this error, even though I assigned the memory using malloc. Any help on this error is appreciated.

#include <stdio.h>  
 struct hello{  
  int i;  
};  
struct proc{  
  int j;  
  struct hello *hello[20];  
};  
int main()
{  
struct proc *proc;

proc->hello[0] = malloc(sizeof(struct hello));
proc->hello[0]->i =10; 

printf("value of i: %d\n",proc->hello[0]->i);

return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
shivam gupta
  • 337
  • 2
  • 4
  • 18
  • 1
    What I find strange, is that you know you should mallocate something for `proc->hello[0]` to point at, and yet are completely fine with not setting `proc` itself to point at valid memory. – StoryTeller - Unslander Monica Mar 03 '17 at 22:45
  • when you declare `struct proc *proc;`, the variable proc is an uninitialized pointer that doesn't have any memory associated. When you dereference it, i.e. `proc->hello[0]` you get a segmentation fault. Better to have your variable declared like this: `struct proc proc;`, and then use it like this: `proc.hello[0]`. – bruceg Mar 03 '17 at 22:49
  • 1
    Also will be less confusing to name your variables, fields and struct types with different names. – bruceg Mar 03 '17 at 22:50

1 Answers1

1

It would be best practice for you to give your variables names separate from their typing.

so

struct proc *proc;

I would recommend something like

struct proc *my_proc;

However, the reason why you're seg faulting is that you're trying to access your *proc before it has been allocated any memory.

It might be NULL, but, more likely, it contains the memory address of a value equal to whatever left over memory is occupying the space that you should be storing a memory address.

So is it we assume it is NULL then what you have programmed is saying

Start Program
Give me a pointer at NULL
Go to NULL and malloc
-- SEG FAULT-- 

You just need to malloc your *proc

int NUM_PROC = 1;
struct proc *my_proc = malloc(sizeof(struct proc) * NUM_PROC);
brian.reeder
  • 31
  • 1
  • 5
  • 1
    The SO consensus is to _not_ cast the result of `malloc` and friends: http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – yano Mar 03 '17 at 23:36
  • Heh, yeah. One of many things I learned on SO. In school, I was always taught to cast. In c++ you have to cast or you get a compiler error I believe – yano Mar 04 '17 at 04:16