数组中的Malloc给出了分段错误

数组中的Malloc给出了分段错误,c,malloc,C,Malloc,在我试图理解malloc和structs时,遇到了一个我不理解的错误 #include <stdio.h> #include <stdlib.h> typedef struct match { int round; } match; void foo(match *matches) { for(int i = 0; i < 10; i++) { matches = (match *) realloc(matches, i + 1);

在我试图理解malloc和structs时,遇到了一个我不理解的错误

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

typedef struct match
{
   int round;
} match;

void foo(match *matches) {
   for(int i = 0; i < 10; i++) {
      matches = (match *) realloc(matches, i + 1);
      matches[i].round = i + 1;
   }
}

int main()
{
   match *matches;

   matches = (match *) malloc(0);

   foo(matches);

   free(matches);

   return(0);
}
#包括
#包括
typedef结构匹配
{
整数轮;
}匹配;
无效foo(匹配*匹配){
对于(int i=0;i<10;i++){
匹配=(匹配*)realloc(匹配,i+1);
匹配[i]。舍入=i+1;
}
}
int main()
{
匹配*匹配;
匹配=(匹配*)malloc(0);
foo(火柴);;
免费(火柴);
返回(0);
}

因此,在我尝试动态填充此匹配数组时,它失败了

您的
foo
函数存在严重缺陷。首先,参数传递
匹配
指针的副本,因此当您realloc时,它更新
foo
匹配
指针,但不更新
中的
匹配
指针。这可能会导致main中的
free
出现问题。您需要将参数更改为
foo
以成为双指针:
void foo(match**matches)
。然后到realloc,
*匹配=realloc(…


接下来,
realloc
的第二个参数是一个大小。但是
i+1
的大小不足以容纳
match
struct的完整副本。您可能打算执行类似于
sizeof(struct match)*(i+1)的操作

您的
foo
函数有很大缺陷。首先,参数传递了
匹配的
指针的副本,因此当您realloc时,它会更新
foo
匹配的
指针,但不会更新
中的
匹配的
指针。这可能会导致主
中的
免费
出现问题。您需要d将参数更改为
foo
为双指针:
void foo(match**matches)
。然后更改为realloc,
*matches=realloc(…


接下来,
realloc
的第二个参数是一个大小。但是
i+1
对于
match
struct的完整副本来说是不够大的。您可能想做一些类似于
sizeof(struct match)*(i+1)
的事情来补充上述答案。很好的解释。。。 在使用内存之前,请检查realloc中的错误

修改程序

void foo(match **matches) {
   for(int i = 0; i < 10; i++) {
      *matches = realloc(*matches, (i+1) * sizeof(match));
      ...
   }
}

int main()
{
...

   foo(&matches);
...
}
void foo(匹配**匹配){
对于(int i=0;i<10;i++){
*匹配项=realloc(*匹配项,(i+1)*大小(匹配项));
...
}
}
int main()
{
...
foo&matches;
...
}

我补充了上述答案。很好的解释。。。 在使用内存之前,请检查realloc中的错误

修改程序

void foo(match **matches) {
   for(int i = 0; i < 10; i++) {
      *matches = realloc(*matches, (i+1) * sizeof(match));
      ...
   }
}

int main()
{
...

   foo(&matches);
...
}
void foo(匹配**匹配){
对于(int i=0;i<10;i++){
*匹配项=realloc(*匹配项,(i+1)*大小(匹配项));
...
}
}
int main()
{
...
foo&matches;
...
}
why malloc(0)?
matches=(match*)realloc(matches,i+1);
why malloc(0)?
matches=(match*)realloc(matches,i+1);