c - 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 中的所需分配大小。我还将图像更新为新的输出。
我希望这更好,更接近检查是否可以分配内存的最终目标。
感谢所有的帮助。谢谢!
解决方案
推荐阅读
- r - 如何从与 R 中的 df 列中的名称不匹配的文件夹中删除某些文件
- javascript - 使用纯 javascript 或 es6 从 json 文件导入数据
- ruby-on-rails - 如何在 Rails 中调试 FactoryGirl.create 回调错误?
- android - 通过 ADB 关闭特定应用程序的自动更新?
- python - 如何在 BS4 中搜索包含给定字符串的标签?
- c# - 基类的依赖注入
- java - 无法实例化扩展 java.util.List 的类
- r - 如何使用多条染色体计算基因之间的距离
- javascript - jquery最接近的h2值?
- scala - scala流处理,计算每个日期的出现次数