0

I have these vars:

uint32_t fsize;
char *filebuffer = NULL;
fsize = fileStat.st_size;

if i want to malloc the right memory the code that i have to write is this:

malloc(fsize);

or this:

malloc(fsize * sizeof(char *));

thanks!

polslinux
  • 1,739
  • 9
  • 34
  • 73

3 Answers3

5

sizeof(char*) is the size of a pointer, which is probably not what you want. Going by the names, I'm assuming that fsize is the size of a file (in bytes), so plain old

malloc(fsize);

is fine.

malloc() allocates the specified number of bytes. If you were to call malloc(fsize * sizeof(char *)) you'd be allocating too much memory, as you're multiplying the required number of bytes (fsize) by an extra factor, sizeof(char*), which is the number of bytes needed to store a pointer (typically 4 or 8 bytes).

The fact that you ultimately assign the allocated memory to a char* pointer is irrelevant when deciding how many bytes to allocate.

Graham Borland
  • 60,055
  • 21
  • 138
  • 179
1

You wrote:

if i want to malloc the right memory the code that i have to write is this:

malloc(fsize); or this:

malloc(fsize * sizeof(char *));

The difference between these two statements is malloc(fsize) gives you memory enough to store the characters in the file, malloc(fsize * sizeof(char *)) give you the memory enough to store the address of enough pointers to point to every character in the file.

I think what you ment to ask was:

"or this: malloc(fsize * sizeof(char));"

in other words do I want to malloc the number of characters in the file times the size of each character, which is a reasonable question, but for characters it's irrelevant because the sizeof(char) = 1. So lets says your file is text and has 4 letters in it:

malloc(fsize) == malloc(4)
malloc(fsize * sizeof(char)) == malloc(4 * 1) == malloc(4)
malloc(fsize * sizeof(char *)) == malloc(4 * 4) == malloc(16)

The reason it's 4 is because you're not getting the size of the data, but the size of the address (ex: 0x0035F900) in bytes.

Hope that helps clarify the answer.

Mike
  • 47,263
  • 29
  • 113
  • 177
0

malloc(size) function allocates a block of size bytes of memory, returning a pointer to the beginning of the block. Like this:

uint32_t fsize = fileStat.st_size;
char* filebuffer = (char*)malloc(fsize);

and don't forget about

free(filebuffer);
Tutankhamen
  • 3,532
  • 1
  • 30
  • 38