我正确加载我的角色阵列吗?

时间:2012-05-20 19:22:53

标签: c arrays pointers malloc valgrind

我已经盯着这么久,所有人都开始一起跑 所以我得到一个valgrind错误:

==25468== Invalid write of size 4
==25468==    at 0x52CF64D: _IO_vfscanf (vfscanf.c:1857)
==25468==    by 0x52D730A: __isoc99_fscanf (isoc99_fscanf.c:35)
==25468==    by 0x402DDB: loadMindRAW (gplib.c:172)
==25468==    by 0x4047EE: loadAgent (gplib.c:739)
==25468==    by 0x4048BD: loadAgentsFromFile (gplib.c:799)
==25468==    by 0x4010C3: initRound (gpfight.c:220)
==25468==    by 0x400EBE: main (gpfight.c:99)
==25468==  Address 0x584388d is 253 bytes inside a block of size 256 alloc'd
==25468==    at 0x4C2B6CD: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)

这是罪犯:

void loadMindRAW(FILE* f_file, unsigned char* mind)
{
    int i;
    for(i=0; i < MIND_SIZE; i++)
    {
        fscanf(f_file,"%d,",&(mind[i]));
    }
}

传入的无符号字符数组之前是malloced: (MIND_SIZE为256)

tmpAgent->mind = malloc(MIND_SIZE*sizeof(unsigned char));
loadMindRAW(f_file, tmpAgent->mind);

我是否正确指出了我的心灵地址? &(mind[i])似乎有点笨拙。原始指针操作mind+i具有相同的行为。我在这里错过了一些简单的东西吗?

1 个答案:

答案 0 :(得分:4)

您正确指向该地址,但您可能无法在指向unsigned char指针的位置向fscanf传递int指针。这是因为fscanf看到%d说明符,它假定可变参数列表中的对应位置是指向签名int的指针;由于varargs在C和C ++中的实现方式,fscanf没有别的办法。

以下是重写循环的方法:

for(i=0; i < MIND_SIZE; i++)
{
    int tmp;
    fscanf(f_file,"%d,",&tmp);
    mind[i] = (unsigned char)tmp;
}