C 中重新分配无效指针

发布于 2024-12-11 15:37:00 字数 182 浏览 0 评论 0原文

这是一项家庭作业,所以我不想发布任何代码,但我对我所遇到的错误感到非常困惑。

目前我有一个已分配空间的数组,并将指针复制到该数组。现在,我可以使用这个数组进行 m​​emcpy 和 memmove,效果很好。

然而,当我用它进行重新分配时,会出现无效指针错误 - 我完全不知道为什么。

有人可以帮忙吗?

This is a homework assignment so I don't want to post any code, but I'm pretty stumped with the bug that I have.

Currently I have a array that has been malloced and am copying the pointer to the array. Now, I can memcpy and memmove with this array and that works fine.

However, when I do a realloc with it an invalid pointer error comes up - and I have absolutely no idea why.

Can anyone help?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

不必在意 2024-12-18 15:37:00

仅当您传递的指针是之前从 malloc()calloc()realloc( 返回的指针时,realloc() 才起作用。 ) (或者是 NULL,在这种情况下它的工作方式与 malloc() 完全相同)。

您不能在数组上调用它。如果您有这样的struct

struct foo {
    char a;
    int x[5];
    double z;
};

那么您不能使用realloc() 来增加x 的大小。您必须改为使用完全动态分配:结构成员更改为指针:

struct foo {
    char a;
    int *x;
    double z;
};

...当您创建 struct 的实例时,您调用 malloc()对于初始分配:

struct foo f;

f.x = malloc(5 * sizeof f.x[0]);

现在您可以在 fx 上调用 realloc(),但代价是您还必须在 fx 上调用 free() code>fx 当不再需要该结构时。

realloc() only works if the pointer you pass it was one returned earlier from malloc(), calloc() or realloc() (or is NULL, in which case it works exactly like malloc()).

You can not call it on arrays. If you have a struct like this:

struct foo {
    char a;
    int x[5];
    double z;
};

then you cannot use realloc() to increase the size of x. You must instead switch to using entirely dynamic allocation: the struct member changes to a pointer:

struct foo {
    char a;
    int *x;
    double z;
};

...and when you create an instance of the struct, you call malloc() for the initial allocation:

struct foo f;

f.x = malloc(5 * sizeof f.x[0]);

Now you can call realloc() on f.x, but the cost is that you must also call free() on f.x when the struct is no longer needed.

人间不值得 2024-12-18 15:37:00

reallocfree导致无效指针错误或段错误时,并且您确信您正在传递从获得的有效指针malloc,那么很可能您损坏了内存:您写入了 malloc 存储内存块簿记的区域。在您的情况下,这是一个 memcpymemmove 调用。

您可以使用 valgrind 内存错误检测器来帮助您找到此类错误。

When realloc or free result in an invalid pointer error or segfault, and you are sure that you are passing a valid pointer obtained from malloc, then a good possibility is that you corrupted your memory: You wrote to the area where malloc stores the book keeping of the memory blocks. In your case this is a memcpy or memmove call.

You can use the valgrind memory error detector to help you find these kind of errors.

梓梦 2024-12-18 15:37:00

你说“我将指向该数组的指针复制到另一个变量中”。问题是一旦进行重新分配,原始指针就不再有效。我不明白将指针复制到变量的原因?

you said 'I copy the pointer to this array into another variable'. The problem is as soon as you do a realloc, the original pointer is no longer valid. I dont see the reason to copy the pointer to a variable?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文