簡體   English   中英

在 Struct 上下文中未使用 printf 時出現段錯誤

[英]Seg fault when printf is not used in a Struct context

我嘗試解決添加了數據和功能的結構。 總的來說,這是可行的,但是當 Struct 只是 init 並且設置了值而不是打印時,這會導致 Seg Fault,可能只是我懷疑有問題,並且當代碼變得更復雜時可能會導致麻煩。

這里是不使用 printf 時出現段錯誤的代碼:

#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);
}
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;
}

您正在嘗試在為其分配內存之前取消引用buf

  t_vec2 *buf;
  buf->size = 2;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM