这是在 c 中释放内存的可接受的方法吗?

1 c memory malloc allocation realloc

我有一个函数,它读取文件并为文件内容分配内存,并将文件内容分配给指针,然后返回指针。然后,我使用循环来遍历字符串并使用指针算术打印每个字符。

我很确定我可以/应该使用 realloc 在每次迭代中重新分配更少的内存,而不是使用计数器跟踪迭代,但我不确定如何实现它。

因此,在代码末尾,当我调用时,free()我从指针变量中减去计数器,以释放contents指针最初指向的地址。

下面是我用来读取文件的代码以及循环所在的主函数:

char *read_file(const char *filename) {
    FILE *fp = fopen(filename, "r");
    if (fp == NULL) {
        perror("Failed to open file");
        exit(EXIT_FAILURE);
    }

    // Obtain information about the file
    struct stat st;
    if (fstat(fileno(fp), &st) != 0) {
        perror("Failed to get file information");
        exit(EXIT_FAILURE);
    }
    size_t file_size = st.st_size;

    // Allocate a buffer to hold the contents of the file
    char *buffer = (char *) malloc(file_size + 1);
    if (buffer == NULL) {
        perror("Failed to allocate memory");
        exit(EXIT_FAILURE);
    }

    // Read the contents of the file into the buffer
    size_t bytes_read = fread(buffer, 1, file_size, fp);
    buffer[bytes_read] = '\0';

    // Close the file and return the buffer
    fclose(fp);
    return buffer;
}




int main() {
    char *contents = read_file("testNote.txt");
    int counter = 0;

    while (*contents != '\0') {

        printf("%c", *contents);

        ++counter;
        ++contents;
    }

    free(contents - counter);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

据我所知,经过实验后,这是按照我的想法工作的,但我只是想确保我在这里没有做任何有害的事情

dbu*_*ush 6

你正在做的事情将会起作用。每次递增 时contents,也会递增counter,因此contents - counter为您提供了可以释放的原始指针。

当然,更好的方法是使用临时指针来递增分配的内存,这样您就可以使用原始的 to free

int main() {
    char *contents = read_file("testNote.txt");
    char *tmp = contents;

    while (*tmp != '\0') {

        printf("%c", *tmp);

        ++tmp;
    }

    free(contents);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)