gpt4 book ai didi

c - Strlen Valgrind 无效读取大小 1

转载 作者:行者123 更新时间:2023-12-04 09:41:19 25 4
gpt4 key购买 nike

在这个程序中,我试图获取存储在文件中的信息,然后搜索它以找到存储的数字。我删除了遍历文件以查找存储的数字的部分,因为该部分工作正常。但是,在本节中,第 63 行(带有 strlen 的那个)有一个错误导致 valgrind 错误报告

==4149== Memcheck, a memory error detector
==4149== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==4149== Using Valgrind-3.12.0.SVN and LibVEX; rerun with -h for copyright info
==4149== Command: main.o
==4149==
==4149== Invalid read of size 1
==4149== at 0x4C2EDB4: strlen (vg_replace_strmem.c:454)
==4149== by 0x108B9E: main (main.c:63)
==4149== Address 0x54de5f7 is 0 bytes after a block of size 23 alloc'd
==4149== at 0x4C2BBAF: malloc (vg_replace_malloc.c:299)
==4149== by 0x108B62: main (main.c:56)
==4149==

这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int findSize(char file_name[]) {
// opening the file in read mode
FILE *fp = fopen(file_name, "r");

// checking if the file exist or not
if (fp == NULL) {
printf("File Not Found!\n");
return -1;
}

fseek(fp, 0L, SEEK_END);

// calculating the size of the file
int res = ftell(fp);

// closing the file
fclose(fp);

return res;
}

int main() {
char *buffer = 0; //contents of the file
long int is = 0; // thing that will be returned
long int ie = 0; // thing that will be returned
int index1; //index of "s"
int index2; //index of "e"
char *a; //phrase after s
char *b; //phrase after e
int bufferlength; //length of txt file
int negativeCount1 = 0;
int negativeCount2 = 0;
long length;
char file_name[] = { "filename" };
FILE *f = fopen(file_name, "rb");

int res = findSize(file_name);
if (res != -1)
printf("Size of the file is %d bytes \n", res);
if (res == 0) {
printf("empty file detected");
return 0;
}

if (f) {
{
fseek(f, 0, SEEK_END);
length = ftell(f);
fseek(f, 0, SEEK_SET);
buffer = malloc(length);
if (buffer) {
fread(buffer, 1, length, f);
}
fclose(f);
}
bufferlength = strlen(buffer);
printf("%d \n", bufferlength);
}
}

最佳答案

在 C 字符串中是 零终止 - 字符串的最后一个元素必须为零。万一所有 length您从文件中读取的字符是非零的,strlen()搜索零字节时将读取缓冲区的末尾。

如果你有它,你可以使用 strnlen()限制缓冲区的最大长度 strlen()将尝试测量:

 bufferlength = strnlen(buffer, length);
// you can also limit printf
printf(".*s\n", (int)length, buffer); // pendantics would check if length <= INT_MAX

或者通常多分配一个字节并确保最后一个字节为零,以便 strlen()后面不读 buffer .
  buffer = malloc(length + 1); // allocate one more
// your error handling of failed allocation is strange
if (buffer != NULL) {
abort();
}
buffer[length] = '\0'; // null terminate buffer
fread (buffer, 1, length, f);
fclose (f);
bufferlength = strlen(buffer); // will read at max `length + 1` characters,
// because `buffer[length] = '\0'`
printf("%s\n", buffer); // buffer is zero terminated - valid

关于c - Strlen Valgrind 无效读取大小 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62318077/

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