在此程序中,我试图获取存储在文件中的信息,然后在文件中进行搜索以找到存储的号码。我删除了我遍历文件以查找所存储编号的部分,因为该部分可以正常工作。但是,在本节中,第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字符串中为零终止