没有失败)并尝试-6ren">
gpt4 book ai didi

c - "Access violation writing location 0x00000000457E8770"在C中使用malloc

转载 作者:行者123 更新时间:2023-11-30 14:53:38 25 4
gpt4 key购买 nike

我遇到了上面的错误,我会尽力尽可能清楚。

简短说明:

我正在定义一个新的结构:kid,并且我想在内存中为kid类型的新数组分配空间。所以我正在执行 malloc (通过我的检查 -> 没有失败)并尝试写入数组的字段之一,但我在标题中收到错误。我不明白为什么我不能在这些字段中写入,即使我做了动态分配。

带注释的代码:

我定义了一个名为 Kid 的结构,如下所示:

 typedef struct
{
char name[16];
candy *kid_candy;
} kid;

(candy是我定义的另一个结构体,我不需要复制他的定义)

上面的定义写在h文件中,该文件包含在下面的代码中。

#include "kindergarten.h"
void AllocateKidsArray(int size);

int main()
{
AllocateKidsArray(3);
}

void AllocateKidsArray(int size){

kid *p_kids_arr = NULL;
int i ;
char blank[16] = {' '};

//In the next line want to allocate space for an array,that his type is kid:
p_kids_arr = (kid*)malloc(size * sizeof(kid));

// checking if allocation failed
if (p_kids_arr == NULL)
{
return -1;
}
else
{
for (i = 0; i < size; i++)
{

//now im trying to change a field in the array I allocated before:
(p_kids_arr + sizeof(kid)*i)->kid_candy = NULL;
//but I always get the error from the title
}

}
}

摘要:

当我在网上寻找解决方案时,大多数遇到该错误的人都是因为他们静态声明了一个指针,然后尝试写入其中。但就我而言,我在进行 malloc 时,我只是无法弄清楚问题是什么,这很令人不安,因为它看起来像是一些基本的东西。

对我来说,了解我缺少什么以及我做错了什么非常重要,我不需要任何代码修复,我想要的只是了解为什么我不能写入动态分配的字段,这就是为什么我需要你的帮助。

谢谢!

最佳答案

为什么不替换这个

      (p_kids_arr + sizeof(kid)*i)->kid_candy = NULL;

这样:

      p_kids_arr[i].kid_candy = NULL;

上面两个不一样。因为如果我向 int 类型的指针加 1实际上,由于指针算术,您要向其添加 4 个字节(如果 int 指针的大小是 4 个字节)(因此我认为第一个版本向 p_kids_arr 添加了比需要的更多的字节。)

正如评论中所指出的,您似乎缺少 #include <stdlib.h>

并且您应该收到警告,因为您正在执行 return -1;在返回类型 void 的函数中.

关于c - "Access violation writing location 0x00000000457E8770"在C中使用malloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47109320/

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