【发布时间】:2015-03-03 10:30:08
【问题描述】:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Person
{
unsigned long age;
char name[20];
};
struct Array
{
struct Person someone;
unsigned long used;
unsigned long size;
};
int main()
{
//pointer to array of structs
struct Array** city;
//creating heap for one struct Array
struct Array* people=malloc(sizeof(struct Array));
city=&people;
//initalizing a person
struct Person Rob;
Rob.age=5;
strcpy(Rob.name,"Robert");
//putting the Rob into the array
people[0].someone=Rob;
//prints Robert
printf("%s\n",people[0].someone.name);
//another struct
struct Person Dave;
Dave.age=19;
strcpy(Dave.name,"Dave");
//creating more space on the heap for people.
people=realloc(people,sizeof(struct Array)*2);
//How do I know that this data is safe in memory from being overwritten?
people[1].someone=Dave;
//prints Dave
printf("%s\n",people[1].someone.name);
//accessing memory on the heap I do not owe?
people[5].someone=Rob;
//prints "Robert" why is this okay? Am I potentially overwriting memory?
printf("%s\n",people[5].someone.name);
return 0;
}
在上面的代码中,我尝试创建一个指向动态结构数组的指针,不确定我是否在这部分成功,但我主要关心的是我使用 malloc 在堆上为数组“people”创建空间。稍后在代码中,我创建了另一个结构 Person 并使用 realloc 在堆上为“人”创建更多空间。然后,我通过执行 'people[5].someone=Rob;.' 在我认为给空间的内容之外写入内存。这仍然有效,因为我可以访问该内存位置的值。我的问题是为什么这行得通?我是否有可能通过写入我没有专门为人们定义的内存来覆盖内存?我实际上是否正确使用了 malloc 和 realloc ?正如我确实听说有一些方法可以测试它们是否在另一篇文章中成功。我是 C 的新手,所以如果我的假设或术语不正确,请纠正我。
【问题讨论】:
-
请告诉我这是作业。如今,任何人都不应该用 C 编写这样的最终用户应用程序代码。
-
这是我自己练习/自学,对我如此赤裸裸。啊,是的,忘记了解放人,但这并不能回答我的问题。
-
您绝对是在写入不属于您的内存。有时,幸运的是,该内存存在并且没有被用于其他任何事情,而事情恰好起作用。不过,不要指望这一点。
-
“为什么会这样”你正在调用未定义的行为。更糟糕的是,您将观察到的行为等同于定义的行为。您的
people[5].someone=Rob;位于people指向的已分配内存区域之外。因此,您的程序格式不正确,并且它表现出的任何行为都不能等同于任何确定的行为。你(不)幸运的是它“有效”。 -
谢谢,我只是在确认。对于更复杂的代码,有没有办法让我知道我只是在访问我拥有的内存?还是保护我不犯这样的愚蠢错误?
标签: c memory heap-memory