gpt4 book ai didi

c - valgrind - 地址是分配的大小为 16 的 block 之前的 2 个字节

转载 作者:行者123 更新时间:2023-11-30 16:22:49 28 4
gpt4 key购买 nike

我在尝试理解为什么 valgrind 告诉我我在 char *array 中超出范围时遇到了一些问题。

每当我尝试从 nul 字节之前开始向后迭代数组时。它向我抛出错误,指出我正在访问不应该访问的内存。

这是我的第一个函数:

char *ReadLineFile(FILE *infile) {
int initSize = 16;
char *string = NULL;
string = malloc(sizeof(char) * initSize);
if(string == NULL){
exit(-1);
}

char val;
int valSize = 0;
while((val = fgetc(infile)) != EOF){
if(val == '\n'){
break;
}

if(valSize == initSize){
initSize *= 2;
string = realloc(string, initSize * sizeof(char));
}

string[valSize++] = val;
}

if(valSize == initSize){
initSize++;
string = realloc(string, initSize * sizeof(char));
}

string[valSize++] = '\0';

return trimString(string);
}

这是我的第二个功能:

char *trimString(char *string) {
int start = 0;
int end = strlen(string);

while(string[start] == ' '){start++;}
while(string[end-2] == ' '){end--;} // the [end-2] causes the error in valgrind

int trimLen = end - start;
char *trimmedStr = malloc(sizeof(char) * (trimLen + 1));
if(trimmedStr == NULL){
exit(-1);
}

int i = 0;
while(start != end){
trimmedStr[i] = string[start];
i++; start++;
}

trimmedStr[i] = '\0';
free(string);

return trimmedStr;
}

Valgrind 错误:

==3809== Invalid read of size 1
==3809== at 0x1090D5: trimString (myio.c:129)
==3809== by 0x109080: ReadLineFile(myio.c:120)
==3809== by 0x108C54: main (driver2.c:29)
==3809== Address 0x522e03e is 2 bytes before a block of size 16 alloc'd
==3809== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload/memcheck-amd64-linux.so)
==3809== by 0x108F91: ReadLineFile(myio.c:90)
==3809== by 0x108C54: main (driver2.c:29)

我希望 valgrind 不会出现错误,因为我在字符串中分配了足够的内存,但它告诉我,当我尝试向后迭代数组时,我正在尝试访问不应该访问的内存。我希望了解导致此错误的原因,因为我花了多个小时试图找出此错误。谢谢!

最佳答案

如果该行只是空格或空行怎么办?

在这种情况下,while(string[end-2] == ' '){end--;} 可能会到达行的开头并继续“向后”行走。

考虑测试行/字符串的限制。另外,为什么是-2?为什么不是-1?即:

while(end > start && string[end - 1] == ' ') --end;

这种方法可以防止你“走”得太远。

旁注:

EOF 标记不是有效字节(不在 0-255 值范围内)。如果是,则它可能是文件中间的有效值。

因此,EOF 不能包含在 char 中,您无法测试 char 是否包含 EOF。使用 int val 而不是 char val

关于c - valgrind - 地址是分配的大小为 16 的 block 之前的 2 个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54276709/

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