Home > Enterprise >  Reading a Structure using pointer second time gives segmentation fault error
Reading a Structure using pointer second time gives segmentation fault error

Time:02-25

When I read the second vector using vector_read() function or by intializing it to zero by usign vector_init_zero() I get segementation fault. I have searched it alot still not got the answer why it's happening. If I use only one pointer and don't initiallize it to 0 it works fine. Every other function works fine with single variable of structure pointer.

#include <stdio.h>
#include <stdlib.h>

typedef struct vector_s
{
  int dim;
  float *data_ptr;
} vector_type;

/* Allocate and initialize to 0 a vector with the given dimension */
void vector_init_zeros(vector_type *v_ptr, int dim)
{
  v_ptr->dim = dim;
  v_ptr->data_ptr = (float *)calloc(dim, sizeof(float));
#ifdef DEBUG
  if (v_ptr->data_ptr == 0)
  {
    printf("vector_init_zeros error: calloc returned a null ptr\n");
    exit(1);
  }
#endif
}

/* Free up a vector that was allocated using vector_init_zeros */
void vector_deinit(vector_type *v_ptr)
{
  v_ptr->dim = 0;
  free(v_ptr->data_ptr);
  v_ptr->data_ptr = 0;
}

/* Attempt to read a vector from stdin. */
/* Returns 1 if read successful and 0 otherwise */
int vector_read(vector_type *v_ptr)
{
  int i;
  float next;
  for (i = 0; i < v_ptr->dim; i  )
  {
    if (scanf("%g\n", &next) != 1)
    {
      return 0;
    }
    v_ptr->data_ptr[i] = next;
  }
  return 1;
}

/* w = u   v */
void vector_add(vector_type *u_ptr, vector_type *v_ptr,
                vector_type *w_ptr)
{
  int i;
  for (i = 0; i < v_ptr->dim; i  )
  {
    w_ptr->data_ptr[i] = u_ptr->data_ptr[i]   v_ptr->data_ptr[i];
  }
}

/* v = cv */
void vector_scalar_mult(vector_type *v_ptr, float c)
{
  int i;
  for (i = 0; i < v_ptr->dim; i  )
  {
    v_ptr->data_ptr[i] = v_ptr->data_ptr[i] * c;
  }
}

/* print the compondents of the given vector */
void vector_print(vector_type *v_ptr)
{
  int i;
  for (i = 0; i < v_ptr->dim; i  )
  {
    printf("%f ", v_ptr->data_ptr[i]);
  }
  printf("\n");
}

int main()
{
  int dim;
  int count = 0;
  if (scanf("%d", &dim) != 1)
  {
    printf("Error reading the vector dimension from stdin\n");
    exit(1);
  }
  vector_type *s,*t;

  vector_init_zeros(s, dim);
  vector_init_zeros(t, dim);
  vector_read(s);
  vector_read(t);


}

CodePudding user response:

In main() where you declare s and t, you never initialize them. You can either declare them as structure variables and pass their addresses to the functions with the & 'address of' operator or allocate and deallocate them with malloc() and free() or equivalents.

int main(){
  ...
  vector_type s, t;
  ...
  vector_init_zeros(&s, dim);
  vector_init_zeros(&t, dim);
  vector_read(&s);
  vector_read(&t);
}

or

int main(){
  ...
  vector_type *s, *t;

  s = (vector_type *) malloc(sizeof(vector_type));
  t = (vector_type *) malloc(sizeof(vector_type));
  ...
  
  free(s);
  free(t);
}
  • Related