C语言 malloc 和 realloc 的问题



为什么当我仍然为''留出空间时,在大小为 7 的块分配错误后得到 0 字节?

我尝试分配和重新分配 7 个字节,并将大小变量保持增加 5,以便在添加空终止符时最后总是至少剩下 2 个字节,但我仍然收到 valgrind 错误:

大小为 1 的写入无效:

分配大小为 7 的块后的 0 字节

例如,每当我读取或写入令牌时,我都会在以下行上得到它:

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 directoryn", 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] = '';
                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);
}

以下建议的代码:

  1. 干净地编译
  2. 消除不必要的代码/逻辑
  3. 执行所需的功能
  4. 正确检查错误
  5. 纳入对OP问题的评论
  6. 将评论纳入此答案

现在建议的代码:(已编辑(

#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: %sn", 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] = '';
            puts(token);
            free( token );
            i = 0;
            size = 0;
        }
    }
    free(token);
    fclose(fp);
}

最新更新