fjidsanfklxingdwsf fjidsanfklxingdwsf - 1 year ago 77
C Question

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;

int main()
// vector of floats
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;

Answer Source

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


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;

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().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download