0
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 必须在这里发生,但为什么呢?!

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

4

3 回答 3

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_pointcreate_FigArray。这将创建指针的副本,因此您对该参数所做的任何更改实际上只是对copy. 这意味着您在fig_array之后存储的地址create_FigArray返回的动态内存与之前相同 - 它只是copy函数更改的内存。如果要更改指针,则需要对函数使用双指针参数,然后使用类似

void create_FigArray(fig** fig_point, int fig_size)
{
    *fig_point = malloc(sizeof(fig) * fig_size);
}
于 2012-11-04T22:12:29.107 回答
1

我不知道,但是:

首先你为 fig_point 分配内存:

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

之后,您将 figure 的地址分配给它,您不应该这样做。

fig_point = &figure;

你可以这样做:

figure = *fig_point;
于 2012-11-04T22:13:14.343 回答
1
  • 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 指针。

于 2012-11-04T22:25:14.387 回答