【问题标题】:SegFault in dynamically allocated array of structs, C动态分配的结构数组中的 SegFault,C
【发布时间】:2012-11-04 22:07:59
【问题描述】:
typedef struct {
  double x;
  double y;
  long out_x;
  long out_y;
} coords;

typedef struct {
  char name[FIGURE_LEN + 1];
  int coordcount, size_tracker;
  coords *coordinate;
} fig;

fig figure;
fig * figpoint;

这是从 parser.c 源文件中调用的函数。

void initialize_fig(int n, char * name, double x, double y,
                         fig *fig_point)
{
  printf("inside function\n");
  strncpy(fig_point[n].name, name, FIGURE_LEN + 1);
  fig_point[n].size_tracker = 1;
  fig_point[n].coordinate = malloc(sizeof(coords) * fig_point[n].size_tracker);
  assert(fig_point[n].coordinate != NULL);
  fig_point[n].coordcount = 0;
  fig_point[n].coordinate[fig_point[n].coordcount].x = x;
  fig_point[n].coordinate[fig_point[n].coordcount].y = y;
}

void create_FigArray(fig * fig_point, int fig_size)
{
  fig_point = malloc(sizeof(fig) * fig_size);
  assert(fig_point != NULL);
  fig_point = &figure
}

我首先像这样调用 create_FigArray...

create_FigArray(fig_point, 16);

我在这里没有 seg 错误... 但后来我打电话...

initialize_fig(0, Qe, 10.0000, 10.0000, fig_point);

参数实际上是通过变量传递的,但我只是想证明它们是正确的参数,并举例说明传递了什么值。 无论如何,它击中了

strncpy(fig_point[n].name, name, FIGURE_LEN + 1);

然后停止.. segfault 必须在这里发生,但是为什么呢?!

请帮助、解释并展示如何解决这个问题。谢谢。

【问题讨论】:

  • 请不要在得到答案后编辑问题。这让人很困惑。

标签: c struct segmentation-fault dynamic-allocation


【解决方案1】:

你分配内存,然后你改变指针

fig_point = malloc(sizeof(fig) * fig_size); // allocate here
assert(fig_point != NULL);
fig_point = &figure;  // now you make fig_point point to something else

因此您的fig_point 指针不再指向您动态分配的内存。如果你这样做

fig_point[n]

由于figure 不是数组,因此您正在访问内存外或范围。此外,您将指针 fig_point 直接传递给 create_FigArray。这将创建指针的副本,因此您对该参数所做的任何更改实际上只是对copy 的更改。这意味着您在create_FigArray 之后存储在fig_array 中的地址返回的动态内存与之前相同 - 只是函数更改了copy。如果要更改指针,则需要对函数使用双指针参数,然后使用类似

void create_FigArray(fig** fig_point, int fig_size)
{
    *fig_point = malloc(sizeof(fig) * fig_size);
}

【讨论】:

  • @user1787262 不,不要编辑问题!这会让其他试图回答您问题的人感到非常困惑。
  • 所以说我改变了它,以便函数接受 fig ** fig_point。我需要改变所有的'。'运算符为 '->'
【解决方案2】:

我不知道,但是:

首先你为 fig_point 分配内存:

fig_point = malloc(sizeof(fig) * fig_size);

然后你将图的地址分配给它,你不应该这样做。

fig_point = &figure;

你可以这样做:

figure = *fig_point;

【讨论】:

【解决方案3】:
  • create_FigArray 你这样做: fig_point = malloc(sizeof(fig) * fig_size);然后这个: fig_point = &figure; //figure is a global variable and this causes a memory leak

  • 改为这样写:

void create_FigArray(fig * fig_point, int fig_size)
{
  fig_point = malloc(sizeof(fig) * fig_size);
  assert(fig_point != NULL);
  fig_point = &figure;//Remove this line
}
  • 在你调用initialize_fig()的函数中或某处,确保释放分配的内存。

  • 使用前将所有指针设为NULL,并在处理指针的函数中添加NULL参数检查,并在使用前检查NULL指针。

【讨论】:

    猜你喜欢
    • 2014-08-22
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 2012-03-25
    • 2011-12-13
    相关资源
    最近更新 更多