# Thread: Memory allocation for structures

1. ## Memory allocation for structures

Why do i get a Seg Fault if I run:
Code:
```#include <stdio.h>

struct rec
{
int i;
float f;
char c;
};

int main()
{
struct rec *p;

(*p).i=10;
(*p).f=3.14;
(*p).c='a';
printf("%d %f %c\n",(*p).i,(*p).f,(*p).c);
free(p);
return 0;
}```
but not
Code:
```#include <stdio.h>

struct rec
{
int i;
float f;
char c;
};

int main()
{
struct rec *p;
p=(struct rec *) malloc (sizeof(struct rec));
(*p).i=10;
(*p).f=3.14;
(*p).c='a';
printf("%d %f %c\n",(*p).i,(*p).f,(*p).c);
free(p);
return 0;
}```
can someone explain why exactly.
and do I always have to do p=(struct rec *) malloc(sizeof(struct rec)); ?

2. struct rec *p;
(*p).i=10;
You have absolutely no idea where you just tried to write that integer - usually somewhere unpleasant, which is why the OS steps in with a seg fault.
If you're unfortunate, it will work, thus suckering you into thinking your program is correct, when in fact it isn't.

struct rec *p;
p=(struct rec *) malloc (sizeof(struct rec));
(*p).i=10;
This on the other hand is better - you know exactly where that int is going - into the memory returned by malloc

> and do I always have to do p=(struct rec *) malloc(sizeof(struct rec)); ?
You've always got to initialise your pointers, and malloc is a good way to do it

A less useful way is
struct rec tmp;
struct rec *p = &tmp;

3. Originally posted by Salem
struct rec *p;
p=(struct rec *) malloc (sizeof(struct rec));
(*p).i=10;
This on the other hand is better - you know exactly where that int is going - into the memory returned by malloc
Not necessarily better tho if malloc fails. Best do some error checking before using that pointer!

Code:
```if ((p = (struct rec *) malloc (sizeof(struct rec))) == NULL)
{
/* malloc has failed, bail out or somthing */
}```

4. thanks
yeah, I usually have ERROR checks in my programs
I am going to write a new function
void bail_out(char* error[]);