memcpy导致EXC_BAD_ACCESS [英] memcpy leads to EXC_BAD_ACCESS

查看:135
本文介绍了memcpy导致EXC_BAD_ACCESS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将其他人的C ++转换为(目标)C,但是memcpy有问题.我使用它的方式如下:

I'm converting someone else's C++ to (Objective) C, but I'm having a problem with memcpy. I use it as follows:

memcpy((void *)virtualFlash[virtualFlashAddress], data, dataLength);

变量定义如下:

unsigned char virtualFlash[5 * 1024 * 1024]; // 5MB
NSUInteger virtualFlashAddress; // set to 8 later on
unsigned char *data = (unsigned char *)[recordData bytes]; // recordData is an NSData object
NSUInteger dataLength = [recordData length]; // same NSData object

我在memcpy的行上得到一个EXC_BAD_ACCESS.我调试了recordData,它返回了<d8ffbd27 2000b1af 1c00b0af 2400bfaf>,并且调试了dataLength,它返回了16,两者都是正确的.

I get an EXC_BAD_ACCESS on the line of the memcpy. I debugged recordData, which returned <d8ffbd27 2000b1af 1c00b0af 2400bfaf>, and dataLength, which returned 16--both correct.

memcpy((void*)virtualFlash[8], data, 16);

此崩溃.我已经读到memmove有时可以工作,但在我的情况下却不行(相同的EXC_BAD_ACCESS).我不确定该怎么做,因为它几乎完全是从可以正常工作的C ++程序复制而来的.我对C的知识非常少,所以我可能会遗漏一些明显的东西.

This crashes. I've read that memmove works sometimes, but not in my case (same EXC_BAD_ACCESS). I'm unsure what to do, as this is almost exactly copied from the C++ program in which it works fine. My knowledge of C is very minimal, so I may be missing something obvious.

推荐答案

unsigned char virtualFlash[5 * 1024 * 1024]; // 5MB

您的堆栈可能足够大,也可能不足以容纳5MB的分配.即使是这样,也确实会有所推动,我会动态分配该金额. 下一个问题:

Your stack may or may not be large enough to accomodate a 5MB allocation. Even if it is, that's really pushing it a bit and I would allocate that amount dynamically. Next problem:

(void *)virtualFlash[virtualFlashAddress]

virtualFlash[virtualFlashAddress]返回一个char,不太可能是有效地址.好像您要写:

virtualFlash[virtualFlashAddress] returns a char, unlikely to be a valid address. Seems like you meant to write:

virtualFlash + virtualFlashAddress

其中virtualFlashAddress是应用于基地址virtualFlash(即数组中第一个元素的地址)的偏移量.

Where virtualFlashAddress is an offset applied to the base address virtualFlash (i.e., the address of the first element in the array).

名称virtualFlashAddress令人困惑,因为它被用作该数组的索引,但这是我最好的猜测,而无需查看更多代码.

The name virtualFlashAddress is confusing as it is being used as an index into that array, but that's my best guess without seeing more code.

这篇关于memcpy导致EXC_BAD_ACCESS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆