gpt4 book ai didi

C : Valgrind telling "Invalid write of size 4" but can't locate the problem

转载 作者:行者123 更新时间:2023-11-30 14:33:15 24 4
gpt4 key购买 nike

我对 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);

那么我哪里缺少内存分配?

最佳答案

所以我设法通过修改代码结构解决了这个问题:

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;
}

关于C : Valgrind telling "Invalid write of size 4" but can't locate the problem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59440815/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com