Sanket Joshi
Sanket Joshi

Reputation: 158

I am trying to allocate dynamic memory to element of structure and getting segmentation fault

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

Answers (3)

Sucheta AB
Sucheta AB

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

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

Bathsheba
Bathsheba

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

Related Questions