当我仍然为 '\0'
留出空间时,为什么在分配大小为 7 的 block 后出现 0 字节错误?
我尝试分配和重新分配 7 个字节,并将大小变量保持增加 5 个字节,这样当我添加空终止符时,末尾总是至少剩下 2 个字节,但我仍然收到 valgrind 错误:
Invalid write of size 1:
0 bytes after a block of size 7 alloc'd
每当我读取或写入 token 时,例如我都会在这一行上得到它:
token[i] = read;
void parse_file(char file[]) {
char read = 0;
int size = 5;
char *token = NULL;
int i = 0;
FILE *fp = NULL;
token = malloc(7 * sizeof(char));
fp = fopen(file, "r");
if(fp == NULL) {
fprintf(stderr, "%s: No such file or directory\n", file);
free(token);
fclose(fp);
return;
}
read = fgetc(fp);
while(read != EOF) {
if(i == size) {
token = realloc(token, 7 * sizeof(char));
size += 5;
}
if(isalpha(read)) {
read = (char) tolower(read);
token[i] = read;
}
else {
if(isalpha(token[0])) {
token[i] = '\0';
put(token);
}
else {
free(token);
}
token = calloc(7,sizeof(char));
size = 5;
i = 0;
read = fgetc(fp);
continue;
}
read = fgetc(fp);
i++;
}
free(token);
fclose(fp);
}
最佳答案
以下建议代码:
- 干净地编译
- 消除不必要的代码/逻辑
- 执行所需的功能
- 正确检查错误
- 纳入对 OP 问题的评论
- 将评论纳入此答案
现在建议的代码:(已编辑)
#include <stdlib.h> // exit(), EXIT_FAILURE, realloc(), free()
#include <stdio.h> // FILE, fprintf(), fopen(), fgetc(), perror()
#include <ctype.h> // isalpha(), tolower()
#include <errno.h> // errno
#include <string.h> // strerror()
// prototypes
void parse_file(char fileName[]);
void parse_file(char fileName[])
{
int byteRead = 0;
size_t size = 0;
char *token = NULL;
size_t i = 0;
FILE *fp = NULL;
fp = fopen(fileName, "r");
if( !fp )
{
fprintf(stderr, "Can't open %s: %s\n", fileName, strerror(errno));
exit( EXIT_FAILURE );
}
while( (byteRead = fgetc(fp) ) != EOF )
{
char *temp = NULL;
if(i >= size)
{
temp = realloc(token, 7 + size );
if( !temp )
{
perror( "realloc failed" );
free( token );
fclose( fp );
exit( EXIT_FAILURE );
}
// implied else, realloc successful
size += 7;
token = temp;
}
if( isalpha(byteRead) )
{
byteRead = tolower(byteRead);
token[i] = (char)byteRead;
i++;
}
else if( i )
{
token[i] = '\0';
puts(token);
free( token );
i = 0;
size = 0;
}
}
free(token);
fclose(fp);
}
关于c - malloc 和 realloc 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48481073/