首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >malloc()分配空间不足

malloc()分配空间不足
EN

Stack Overflow用户
提问于 2014-05-05 00:34:40
回答 3查看 3.9K关注 0票数 0

你好,这是我的问题

代码语言:javascript
运行
复制
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);

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

代码语言:javascript
运行
复制
char *buffer = (char *) malloc(fSize)

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

谢谢,

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-05-05 00:37:53

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

票数 4
EN

Stack Overflow用户

发布于 2014-05-05 00:38:03

size of (缓冲区)是指针的大小或32位(4字节)。它实际上是分配足够的空间。

票数 0
EN

Stack Overflow用户

发布于 2014-05-05 11:27:44

这也许就是你想要达到的目标。

代码语言:javascript
运行
复制
#include <stdio.h>
#include <stdlib.h>
int  main(int argc, char *argv[])
{
    FILE *sourcefile;
    if ((sourcefile = fopen(argv[1],"r")) == NULL)  //Opens File
    {
        printf("Error: Could not open %s\n",argv[1]);
        eturn 0;
    }
    fseek(sourcefile, 0 , SEEK_END);  // Sets file pointer at the end of the file
    unsigned long fSize = ftell(sourcefile); 
    fseek(sourcefile, 0 , SEEK_SET); // Sets file pointer at the start of the file
    fSize -= ftell(sourcefile);  /*This determines file size  */
    char *buffer = (char *) malloc(fSize); 
    if (buffer == NULL)
    {
    printf("Error: Not enough system memory\n");
    return 0;
    }

    printf("%ld\n",sizeof(buffer)); 
    printf("%ld\n",fSize);
    fread (buffer,1,fSize,sourcefile);
    fclose (sourcefile);
    return 1;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23463223

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档