【问题标题】:Seg fault when printf is not used in a Struct contextStruct 上下文中未使用 printf 时的段错误
【发布时间】:2021-02-12 18:12:19
【问题描述】:

我尝试使用添加了数据和功能的 Struct 来解决问题。总的来说,这是可行的,但是当 Struct 只是 init 并且值设置而不打印时,这会导致 Seg Fault,可能没什么,但我怀疑有问题,并且当代码变得更复杂时,这可能会导致麻烦。

这里是不使用 printf 时出现 seg 错误的代码:

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

【问题讨论】:

  • 你知道valgrind这个工具吗?运行valgrind &lt;your_executable&gt;,它可以帮助您找到内存问题。它非常易于使用且非常功能强大。可能你必须安装它:sudo apt install valgrind
  • @phip1611 是的,我使用 valgrind,但内存泄漏只是一点点......对于我的级别来说非常复杂:(

标签: c struct segmentation-fault malloc


【解决方案1】:
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;

【讨论】:

  • 完美答案,现在在所有情况下都可以正常工作!!!!我还没有好的练习。非常感谢。
猜你喜欢
  • 2010-10-07
  • 2011-02-13
  • 1970-01-01
  • 1970-01-01
  • 2020-11-21
  • 2011-02-27
  • 1970-01-01
  • 1970-01-01
  • 2017-04-19
相关资源
最近更新 更多