C:Valgrind告诉“大小为4的无效写入,但找不到问题的位置

问题描述 投票:0回答:1

我对C相当陌生,无法找到使用Valgrind调试时遇到的错误。这是我得到的错误。

==1987== Invalid write of size 4
==1987==    at 0x108C17: init_TSEQ (sequence.c:51)
==1987==    by 0x1089A8: main (main1.c:14)
==1987==  Address 0x51e5490 is 0 bytes after a block of size 880 alloc'd
==1987==    at 0x4C2BBEF: malloc (vg_replace_malloc.c:299)
==1987==    by 0x108B7E: init_TSEQ (sequence.c:38)
==1987==    by 0x1089A8: main (main1.c:14)

显然,问题出在此功能上。

SEQUENCE *init_TSEQ(int nseq)
{
    DIR *D=opendir("sequences");
    struct dirent *entry;
    SEQUENCE *TSEQ=malloc(sizeof(SEQUENCE)*nseq);
    FILE *F;

    chdir("sequences");

    for(int i=0; (entry=readdir(D))!=NULL; i++)
    {
        if(entry->d_type==DT_REG)
        {
            char seq[MAXSIZE];

            F=fopen(entry->d_name, "r");
            fscanf(F, "%s", seq);
            TSEQ[i].lenght=strlen(seq);  // This is the line where the error comes from (l.51 in the code)

            for (int j=0; j<TSEQ[i].lenght; j++)
            {
                fscanf(F, "%c", seq);
                TSEQ[i].c[j]=seq[j];
            }

            fclose(F);
        }
    }

    closedir(D);

    return TSEQ;
}

这是我正在使用的SEQUENCE结构:

struct sequence
{
    int lenght;
    char c[MAXSIZE]; // MAXSIZE equals to 40
};

typedef struct sequence SEQUENCE;

正如您在函数中所看到的,我在这一行中为TSEQ.lenght字段分配了内存:

SEQUENCE *TSEQ=malloc(sizeof(SEQUENCE)*nseq);

所以我在哪里缺少内存分配?

c memory valgrind allocation
1个回答
0
投票

所以我设法通过修改代码的结构来解决问题:

SEQUENCE *init_TSEQ(int nseq)
{
    DIR *D=opendir("sequences");
    struct dirent *entry;
    SEQUENCE *TSEQ=malloc(sizeof(SEQUENCE)*nseq);
    FILE *F;
    int i=0;

    chdir("sequences");

    while(((entry=readdir(D))!=NULL) && (i<=nseq))
    {
        if(entry->d_type==DT_REG)
        {
            char seq[MAXSIZE];

            F=fopen(entry->d_name, "r");
            fscanf(F, "%s", seq);
            TSEQ[i].lenght=strlen(seq);

            for (int j=0; j<TSEQ[i].lenght; j++)
            {
                fscanf(F, "%c", seq);
                TSEQ[i].c[j]=seq[j];
            }

            fclose(F);
            i++;
        }
    }

    closedir(D);

    return TSEQ;
}
© www.soinside.com 2019 - 2024. All rights reserved.