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 ()
typedef struct v_
// vector of floats
int ele = access_element_vector(vec, 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;
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.
NULL) and put a (
NULL) check for the incoming pointer.
init_vectorwhich 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
main() before passing that to