0

I am trying to write a code that read a size of file then allocate the buffer size accordingly.

for some reason my buffer size is not changing its 4 Bytes always.

Any tips why my buffer is not allocating memory equal to the read file size?

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

int main ()
{
   FILE *file,*fp;

   file = fopen("file.txt", "r");
   fp = fopen( "outputnew.txt" , "w" );

   long lSize;

   fseek(file, 0, SEEK_END);
   lSize = ftell(file);
   fseek(file, 0, SEEK_SET);

   char *buffer = (char*) malloc(sizeof(char)*lSize);
   printf("%d\n",sizeof(buffer));  
   return(0);
}
Bhumi Shah
  • 9,323
  • 7
  • 63
  • 104
  • 3
    Hint #1: [don't cast `malloc`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc); hint #2: [`sizeof(char)` is always `1`](http://stackoverflow.com/questions/2215445/are-there-machines-where-sizeofchar-1) – Crozin Oct 11 '14 at 07:23

3 Answers3

2

malloc is working, but your test of the size of the buffer is wrong. sizeof(buffer) returns the size of the variable buffer, which is a char *. On a 32 bit platform, this will always be 4 bytes. What you want is the size of the heap allocation to which buffer points; there is no easy way to return that. However, your code is correct in that it will allocate a block of size sizeof(char)*lSize

abligh
  • 24,573
  • 4
  • 47
  • 84
1

Your buffer is all right. From the C compiler point of view buffer is char *, therefore sizeof(buffer) is sizeof(char *) aka 4. As long as malloc returns valid (non-null) address you are OK.

user58697
  • 7,808
  • 1
  • 14
  • 28
1

malloc() normally never fails. Or if you want to check if malloc() failed, check the return address you stored in buffer.

if(buffer==NULL) printf("malloc() failed\n");

And sizeof(buffer) returns the size of the pointer variable buffer. It will be 4 bytes on x86 platforms and 8 bytes on x64 platforms.

ninja
  • 809
  • 5
  • 9