我需要一些帮助,因为我的代码在valgrind中抛出了一些错误。代码虽然有效...所以我不明白问题是什么,你们能帮我看看吗?谢谢!
使用编译行:gcc -Wall -pedantic -ansi -g
char* readfile(char *filename) {
FILE *fp;
int size = 0;
char *buffer = NULL;
fp = fopen(filename, "r");
if(fp != NULL) {
/* Grab the size of the file */
fseek(fp, 0L, SEEK_END);
size = ftell(fp);
fseek(fp, 0L, SEEK_SET);
/* Memory allocate char */
buffer = (char*) malloc(size);
if(buffer == NULL) {
printf("ERROR: Memory allocation error!n");
exit(EXIT_FAILURE);
}
/* Read the file and close */
fread(buffer, size, 1, fp);
fclose(fp);
} else {
printf("Failed to open %s filen", filename);
}
return buffer;
}
int main(int argc, char * argv[]) {
struct ets ets;
struct menu_item menu_items[NUM_MENU_ITEMS];
char *filebuffer = 0;
/*if(argc != 4) {
perror("Inputs are not validn");
return EXIT_FAILURE;
}*/
filebuffer = readfile(argv[1]);
printf("Contents: %sn", filebuffer);
free(filebuffer);
return 0;
}
administrator:Assignment 2 Administrator$ valgrind --leak-check=full ./main equip.dat
==3972== Memcheck, a memory error detector
==3972== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==3972== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==3972== Command: ./main equip.dat
==3972==
==3972== Invalid read of size 1
==3972== at 0x828A: strlen (in /usr/local/Cellar/valgrind/3.10.1/lib/valgrind/vgpreload_memcheck-amd64-darwin.so)
==3972== by 0x14BA8C: __vfprintf (in /usr/lib/system/libsystem_c.dylib)
==3972== by 0x14A35E: vfprintf_l (in /usr/lib/system/libsystem_c.dylib)
==3972== by 0x14273F: printf (in /usr/lib/system/libsystem_c.dylib)
==3972== by 0x100000BF1: main (ets_main.c:59)
==3972== Address 0x10001c196 is 0 bytes after a block of size 118 alloc'd
==3972== at 0x6B1B: malloc (in /usr/local/Cellar/valgrind/3.10.1/lib/valgrind/vgpreload_memcheck-amd64-darwin.so)
==3972== by 0x100000B19: readfile (ets_main.c:31)
==3972== by 0x100000BDB: main (ets_main.c:57)
==3972==
你不 null 终止buffer
,malloc
更改为
buffer = malloc(1 + size);
然后在检查malloc
成功后将其添加到某处
buffer[size] = ' ';
将返回的指针传递给printf()
时,它会读取1
字节超过malloc
ed块,因此valgrind
错误。