Reputation: 158
I am trying to allocate dynamic memory to element of array but i am getting segmentation fault This is the code :
#include <stdio.h>
#include <stdlib.h>
struct Octstr
{
unsigned char *data;
long len;
long size;
int immutable;
};
int main()
{
struct Octstr *obj;
obj->data = (char*)malloc(16);
return 0;
}
Upvotes: 1
Views: 50
Reputation: 1
Initialize all your pointers by NULL.And make sure you free it after usage of your pointer at the end of your code.
Upvotes: 0
Reputation: 170269
struct Octstr *obj;
is an uninitialized variable, it stores an unspecified address, and therefore points to an unspecified location.
Dereferencing it by trying to access a member is undefined behavior, which in your case results in a segmentation fault.
Upvotes: 0
Reputation: 234875
You didn't allocate memory for the struct
itself: obj
is uninitialised.
The behaviour of your code is undefined.
Either malloc
some memory for it or use automatic storage duration:
struct Octstr obj;
obj.data = (char*)malloc(16);
Finally, don't forget to balance your malloc
calls with calls to free
. (Also it's unnecessary to cast the return pointer of malloc
in C, and do check the return pointer value to check if the allocation was successful).
Upvotes: 2