The-Han-Emperor
The-Han-Emperor

Reputation: 357

Program gives segmentation fault while trying to malloc for a pointer member of structure

I wrote my code which works well on netbeans, but gives me a seg fault on putty. I tried to use the gdb, but it seems helpless in which gives me

 Program received signal SIGSEGV, Segmentation fault.
 0x00000000004006c1 in init_vector ()
 (gdb) back trace 
  #0  0x00000000004006c1 in init_vector ()
  #1  0x0000000000400664 in main ()

Here is my code, hope someone can help me out

  typedef struct v_
 {
   int* data;
   int size;
   int capacity;
}vector;


   int main()
 {
    // vector of floats
     vector *vec;
     init_vector(vec); 
     insert_element_vector(vec, 5);

     int ele = access_element_vector(vec, 0);
      printf("%d\n", ele);
      return 0;
  }


   void init_vector( vector* v)
{
    v->data = malloc(sizeof(int) * INIT_VECTOR_SIZE);
     v->size = 0;
     v->capacity = INIT_VECTOR_SIZE;
 }



  void insert_element_vector( vector* v, int element_to_insert)
 {
   if(v->capacity == v->size)
   {
        v->data = realloc(v->data, sizeof(int) * v->capacity * 2);
        v->capacity *= 2;
   }
         v->data[v->size] = element_to_insert;
         v->size += 1;
  }

Upvotes: 2

Views: 205

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

In your code, in init_vector() function, you're directy accessing the passed pointer like

  v->data

and more. In case the passed pointer is NULL or invalid, this will invoke undefined behavior.

In your case, vec being an uninitialized automatic local variable, the content is indeterminate. So, the pointer points to invalid memory, essentially. Trying to access it invokes the UB.

To avoid

  1. Always better to initialize the automatic local variables (here, pointer to NULL) and put a (NULL) check for the incoming pointer.
  2. Pass a memory address to init_vector which is valid.

For the second step, you can pass the address of a scalar variable, like

 vector *v;
 init_vector(&v);

to get things working.

Another possibility is, use malloc() or similar allocator function to allocate memory to vec in main() before passing that to init_vecor().

Upvotes: 2

Aganju
Aganju

Reputation: 6395

In main, you declare a *vec;, and then start using it, but it is never associated with any memory. A segmentation fault is exactly what I would expect.

Declare it as vector vec;, and then pass its address to the calls (&vec), and the problem is resolved.

Upvotes: 1

Related Questions