首页 > 解决方案 > C - 这是检查是否达到 malloc'd 大小的有效方法吗?(使用 fgets() + strlen() )

问题描述

有一个想法来测试给定的 char * 是否没有通过分配的 malloc 大小,但是我不确定这是否是一个很好的检查方法。

注意:抱歉代码混乱,缩进有问题。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

bool start_or_reset(int allocated_memory_lenght_size){

printf("allocated_memory_lenght_size: %d\n\n", allocated_memory_lenght_size);
int allocated_memory_lenght_reached = 0;
int line_count = 0, i = 0;

char line[255];
char * file_contents = malloc(allocated_memory_lenght_size);
file_contents[0] = 0;

if (!file_contents){
    perror("Malloc failed. Exiting.\n");
    exit(1);
}

FILE * fp1 = fopen("read_from_this_file.txt", "r");
FILE * fp2 = fopen("read_from_this_file.txt", "r");

if (fp1 == NULL || fp2 == NULL){
    perror("The file doesn't exist. Exiting.\n");
    exit(1);
}

while (fgets(line, sizeof(line), fp1) != NULL){
    line_count++;
}
printf("line count: %d\n", line_count);

while (fgets(line, sizeof(line), fp2) != NULL){
    
    allocated_memory_lenght_reached += strlen(line);
    i++;

    // Add +1 for allocation if \0 is met:
    if (i == line_count)
        allocated_memory_lenght_reached += 1;

    printf("allocated_memory_lenght_reached: %d\n", allocated_memory_lenght_reached);

    if (allocated_memory_lenght_reached > allocated_memory_lenght_size)
        return 1;
    
    strcat(file_contents, line);
}

printf("\nfile_contents:\n\n%s\n", file_contents);

free(file_contents);
fclose(fp1);
fclose(fp2);
return 0;
}

int main(){

bool malloc_is_valid;
int allocated_memory_lenght_size = 56;

// Step 1
// Check if malloc is enough or not, then return 0 or 1
malloc_is_valid = start_or_reset(allocated_memory_lenght_size);

printf("\n0: Malloc successful, 1: Malloc unsuccessful\n");
printf("malloc_is_valid returns: %d\n", malloc_is_valid);

return 0;
}

控制台的新输出: 在此处输入图像描述

我所做的更改:我确保它检查 char * file_contents 的最后一行中的 \0 最后一行,并将 +1 添加到已分配_memory_lenght_reached 中的所需分配大小。我还将图像更新为新的输出。

我希望这更好,更接近检查是否可以分配内存的最终目标。

感谢所有的帮助。谢谢!

标签: cmallocfgetsstrlen

解决方案


推荐阅读