sizeof(buffer)
should be 4 bytes on a 32-bit platform. It is a pointer pointing to the buffer that malloc allocated. There is no way to query it for the size of the buffer.
malloc() not allocating enough space
题
Hello here is my problem
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);
My code is simply opening a file and loading its contents into memory. The problem is, when I use
char *buffer = (char *) malloc(fSize)
it allocates only 4 bytes
and not the full size of the file (i.e. 25 bytes when opening a simple txt with a small sentence). When I print the sizes of buffer
and fSize
at the end, I get 4 and 25 respectively, so fSize
is correct. Any idea why this is happening?
Thanks,
解决方案
其他提示
sizeof(buffer) is the size of a pointer or 32 bits (4 bytes). It is in actuality allocating enough space.
This is maybe what you want to achieve.
#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;
}
不隶属于 StackOverflow