C 中重新分配无效指针
这是一项家庭作业,所以我不想发布任何代码,但我对我所遇到的错误感到非常困惑。
目前我有一个已分配空间的数组,并将指针复制到该数组。现在,我可以使用这个数组进行 memcpy 和 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
仅当您传递的指针是之前从
malloc()
、calloc()
或realloc( 返回的指针时,
(或者是realloc()
才起作用。 )NULL
,在这种情况下它的工作方式与malloc()
完全相同)。您不能在数组上调用它。如果您有这样的
struct
:那么您不能使用
realloc()
来增加x
的大小。您必须改为使用完全动态分配:结构成员更改为指针:...当您创建
struct
的实例时,您调用malloc()
对于初始分配:现在您可以在
fx
上调用realloc()
,但代价是您还必须在fx
上调用free()
code>fx 当不再需要该结构时。realloc()
only works if the pointer you pass it was one returned earlier frommalloc()
,calloc()
orrealloc()
(or isNULL
, in which case it works exactly likemalloc()
).You can not call it on arrays. If you have a
struct
like this:then you cannot use
realloc()
to increase the size ofx
. You must instead switch to using entirely dynamic allocation: the struct member changes to a pointer:...and when you create an instance of the
struct
, you callmalloc()
for the initial allocation:Now you can call
realloc()
onf.x
, but the cost is that you must also callfree()
onf.x
when the struct is no longer needed.当
realloc
或free
导致无效指针错误或段错误时,并且您确信您正在传递从获得的有效指针malloc
,那么很可能您损坏了内存:您写入了malloc
存储内存块簿记的区域。在您的情况下,这是一个memcpy
或memmove
调用。您可以使用 valgrind 内存错误检测器来帮助您找到此类错误。
When
realloc
orfree
result in an invalid pointer error or segfault, and you are sure that you are passing a valid pointer obtained frommalloc
, then a good possibility is that you corrupted your memory: You wrote to the area wheremalloc
stores the book keeping of the memory blocks. In your case this is amemcpy
ormemmove
call.You can use the valgrind memory error detector to help you find these kind of errors.
你说“我将指向该数组的指针复制到另一个变量中”。问题是一旦进行重新分配,原始指针就不再有效。我不明白将指针复制到变量的原因?
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?