2

EXC_BAD_ACCESS当我试图记录这个函数的结果时,我一直在得到一个?我究竟做错了什么?

-(uint64_t) rand64bitNum {
    uint32_t left = arc4random();
    uint32_t right = arc4random();
    uint64_t randNum = 0;
    memcpy(&randNum, &left, sizeof(left));
    uint16_t offset = sizeof(left);
    memcpy(&randNum+offset, &right, sizeof(right));
    return randNum;
}
4

2 回答 2

4

&randnum+offset没有做你认为它做的事;指针加法是以所指向的事物为单位进行的。所以你可能想要(char *)&randnum + offset.

于 2013-05-26T18:59:46.737 回答
4

@OliCharlesworth 的回答中给出了您的内存错误的解释,但我想提出一个完全不需要的更好的解决方案memcpy

- (uint64_t)rand64bitNum
{
    uint64_t left = arc4random();
    uint64_t right = arc4random();
    uint64_t randNum = (right << 32) | left;
    return randNum;
}

也许更好,并且(几乎)没有出错的余地,您可以使用arc4random_buf(3)

- (uint64_t)rand64bitNum
{
    uint64_t randNum;
    arc4random_buf(&randNum, sizeof randNum);
    return randNum;
}
于 2013-05-26T19:02:54.960 回答