memcpy causing 'exc bad access'

a 夏天 提交于 2019-12-11 07:15:40

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/7623602/memcpy-causing-exc-bad-access

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!