gpt4 book ai didi

c - Windows 上的堆损坏操作 C 中的结构指针数组

转载 作者:行者123 更新时间:2023-11-30 15:09:34 24 4
gpt4 key购买 nike

此代码在 Windows(使用 VS2010)和 Linux(使用 gcc)上都可以正常编译。它在 Linux 上运行良好,但在 Windows 上我遇到了堆损坏。这是怎么回事?

代码的目的只是学习如何在 C 中使用指向结构的指针数组。这只是一个玩具示例:您有一个结构体 apple,其中有一个指定排序的字符数组和一个指定权重的 double 。 Basket 是一个包含指向苹果的指针数组的结构。篮子本身还有一些其他参数,例如显示篮子有多满以及里面有多少个苹果。

我尝试使用 VS 中的标志并将其设置为编译为 C 代码 (/TC),但这没有什么区别。所以我的问题是:

  1. 代码有问题吗?

  2. 为什么 Windows 和 Linux 上的结果不同?

这是我的代码:

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

struct Apple{
char *Sort;
double Weight;
};

struct Basket{
struct Apple **apples;
double full;
int numApples;
};

int main()
{
int i;
int numApples = 5;

struct Basket *mybasket = (struct Basket *) malloc(sizeof(structBasket*));
struct Apple **apples;
apples = malloc(numApples*sizeof(struct Apple*));

for(i=0;i<numApples;i++)
{
apples[i] = (struct Apple*)malloc(sizeof(struct Apple*));
apples[i]->Sort = (char *)malloc(18*sizeof(char *));
apples[i]->Weight = ((double)i+1)*0.57;
}

mybasket->apples = apples;
mybasket->full = 0.8;
mybasket->numApples =numApples;

strcpy(apples[0]->Sort, "Fuji");
strcpy(apples[1]->Sort, "Braburn");
strcpy(apples[2]->Sort, "Golden Delicious");
strcpy(apples[3]->Sort, "Red Delicious");
strcpy(apples[4]->Sort, "McIntosh");

for(i=0;i < numApples;i++)
{
printf("\n apple #%d is %s and weights %f pounds",i,mybasket->apples[i]->Sort,mybasket->apples[i]->Weight);
}

printf("\n\n");

for(i=numApples-1;i>-1;i--)
{
free(apples[i]);
}

free(apples);
free(mybasket);
return 0;
}

最佳答案

  1. Is there something wrong with the code?

是的。

  1. struct Basket *mybasket = (struct Basket *) malloc(sizeof(structBasket*)); 应为 struct Basket *mybasket = malloc(sizeof(structBasket));

  2. apples[i] = (struct Apple*)malloc(sizeof(struct Apple*)); 应该是 apples[i] = (struct Apple*)malloc( sizeof(struct Apple));

  3. apples[i]->Sort = (char *)malloc(18*sizeof(char *)); 应为 apples[i]->Sort = malloc (18);

由于T *ptr指向T的“一个数组”,所以调用的内存空间应该是n * sizeof (T) .

此外,为了避免内存泄漏,请在 free() 之前free() 结构体的所有字段:

while(numApples--)
{
free(apples[numApples]->Sort);
free(apples[numApples]);
}
  1. Why are the results different on Windows and Linux?

因为访问尚未分配的内存会调用未定义的行为,在这种情况下,从按预期工作到堆损坏的任何事情都可能发生。它在 Linux 上运行只是因为你(不)幸运。

关于c - Windows 上的堆损坏操作 C 中的结构指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36602512/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com