1

I try to work around a Struct with data and function added. On the whole that's work but when the Struct is simply init and the value set and not print, that's cause a Seg Fault, may be is nothing but I suspect something wrong, and may be that's can cause trouble when the code becomes more complex.

here the code where there is a seg fault when printf is not used :

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

// https://stackoverflow.com/questions/14768230/malloc-for-struct-and-pointer-in-c
typedef struct s_vec2 t_vec2;
struct s_vec2 {
    float *data;
  size_t size;

  void (*set_x)(t_vec2*, float);
  void (*set_y)(t_vec2*, float);
  float (*get_x)(t_vec2*);
  float (*get_y)(t_vec2*);
};

t_vec2 *new_vec2() {
  t_vec2 *buf;
  buf->size = 2;

  if(!(buf = (t_vec2*)malloc(sizeof(t_vec2))))
    return (0);
  
  if(!(buf->data = (float*)malloc(sizeof(float) * 2))) {
    free(buf);
    return (0);
  }

  return buf;
}

void func_set_x(t_vec2 *v, float x) {
  v->data[0] = x;
}

void func_set_y(t_vec2 *v, float y) {
  v->data[1] = y;
}

float func_get_x(t_vec2 *v) {
  return v->data[0];
}

float func_get_y(t_vec2 *v) {
  return v->data[1];
}

int main() {
  t_vec2 *a = new_vec2();
  a->set_x = func_set_x;
  a->set_y = func_set_y;
  a->get_x = func_get_x;
  a->get_y = func_get_y;
  float val = 5;
  a->set_x(a,val);
  a->set_y(a,6);
  // printf("vec %f %f\n",a->get_x(a), a->get_y(a)); // if this line is remove, that's cause a seg fault why ????
  return(0);
}
Knupel
  • 323
  • 2
  • 14
  • Are you aware of the tool `valgrind`? run `valgrind ` and it helps you to find memory issues. It's pretty easy to use and **very** powerful. Probably you have to install it: `sudo apt install valgrind` – phip1611 Oct 30 '20 at 09:29
  • @phip1611 yep I use valgrind, but just a little for the memory leaks... very complex for my level :( – Knupel Oct 30 '20 at 09:44

1 Answers1

3
t_vec2 *new_vec2() {
  t_vec2 *buf;
  buf->size = 2;

  if(!(buf = (t_vec2*)malloc(sizeof(t_vec2))))
    return (0);
  
  if(!(buf->data = (float*)malloc(sizeof(float) * 2))) {
    free(buf);
    return (0);
  }

  return buf;
}

You are trying to dereference buf before allocating memory to it.

  t_vec2 *buf;
  buf->size = 2;
kiran Biradar
  • 12,700
  • 3
  • 19
  • 44
  • 1
    Perfect answer, that's work fine now in all of cases !!!! I haven't the good practice yet. thx a lot. – Knupel Oct 30 '20 at 09:36