memcpy 导致“排除错误访问”
我试图循环遍历一个数组并复制数据,但在 1023 次循环后,我收到一条 exc bad access
消息,我感觉这可能与我的记忆有关。 在我的循环中,我需要将数据附加到我的 totalValues
数组中,所以我这样做了:
memcpy(totalValues + totalCopied, tempBuffer, 600 * sizeof(float));
这是在循环内完成的,并且 totalCopied
跟踪已附加的数据量到totalValues,以便我知道当循环再次命中memcpy时从哪里开始写入。我不确定为什么会收到“exc bad access”错误,但我的理论是内存不连续,因此 totalValues + totalCopied
行可能会造成麻烦。我不确定在这种情况下是否会引发错误,或者内存是否会被覆盖。有趣的是,它总是发生在 1023 次循环之后。如果我删除“memcpy”行,程序将毫无问题地循环运行。有什么想法可能导致这种情况吗?
编辑-原因是内存分配是为另一个文件硬编码的。通常情况下,在分配内存之前我不会知道文件的长度,那么如何确保在运行时分配足够的内存呢?
I'm trying to loop through an array and copy across data, but after 1023 loops, I get an exc bad access
message thrown and I have a feeling it might be to do with my memory.
In my loop, I need to append data to my totalValues
array, so I did this:
memcpy(totalValues + totalCopied, tempBuffer, 600 * sizeof(float));
This is done inside a loop and totalCopied
keeps track of how much data has been appended to totalValues
so that I know where to write from when the loop hits memcpy again. I'm not sure why I get the "exc bad access" error, but my theory is that the memory is not contiguous and, therefore, the totalValues + totalCopied
line might be causing trouble. I'm not sure if an error would be thrown in this case, or if the memory would just be overwritten anyway. The interesting thing is, it always occurs after 1023 loops. If I remove the 'memcpy' line, the program loops through without any problems. Any ideas what could be causing this?
EDIT - The cause was that the memory allocation was hard coded for another file. Normally, I won't know the length of the file before the memory allocation, so how can I ensure that enough memory is allocated at runtime?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来您写入的字节数超出了 TotalValues 所能包含的字节数。向我们展示您如何分配它。
顺便说一句,我们通常在 iOS 上使用 NSData 对象来做这种事情。
Sounds like you're writing more bytes than totalValues can contain. Show us how you're allocating it.
Incidentally, we usually do this kind of thing with NSData objects on iOS.