c - malloc() 没有分配足够的空间

标签 c file-io malloc ftell

你好,这是我的问题

FILE *sourcefile;

if ((sourcefile = fopen(argv[1],"r")) == NULL)  //Opens File
{
    printf("Error: Could not open %s\n",argv[1]);
    return 0;
}

fseek(sourcefile, 0 , SEEK_END);  // Sets file pointer at the end of the file
unsigned int fSize = ftell(sourcefile); // Determines file size by the position of file pointer
fseek(sourcefile, 0 , SEEK_SET); // Sets file pointer at the start of the file

char *buffer = (char *) malloc(fSize); 

if (buffer == NULL)
{
    printf("Error: Not enough system memory\n");
    return 0;
}

printf("%d\n",sizeof(buffer));
printf("%d\n",fSile);

fread (buffer,1,fSize,sourcefile);
fclose (sourcefile);

我的代码只是打开一个文件并将其内容加载到内存中。问题是,当我使用

char *buffer = (char *) malloc(fSize)

它只分配了 4 个字节 而不是文件的完整大小(即打开带有小句子的简单 txt 时为 25 个字节)。当我最后打印 bufferfSize 的大小时,我分别得到 4 和 25,所以 fSize 是正确的。知道为什么会这样吗?

谢谢,

最佳答案

sizeof(buffer) 应该 在 32 位平台上为 4 字节。它是指向 malloc 分配的缓冲区的指针。无法查询缓冲区的大小。

关于c - malloc() 没有分配足够的空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23463223/

相关文章:

c - 修改链表中结构体的字段

python - 在我的批处理文件重命名和移动脚本中遇到 Python os.rename() 问题

Java无法创建新进程: too many open file error

c - 在 cortex m3(裸机)上使用 arm-none-eabi 禁用默认 malloc

c - valgrind 地址是大小为 4 的 block 分配后的 0 字节

c - 内存竞技场和内存池有什么区别?

c - 它们是否不同 : converting type of pointer then get data AND getting data of pointer then convert datatype

c - 为了防止段错误,atexit() 函数应该放在哪里?

python - 使用相对于目录/文件描述符的路径截断文件?

c - 我的 char vector 在每个位置保存相同的值