Question

When I use

  fstat(fileno(file), &st); //struct stat st

  buf = malloc(fsize);   //size_t fsize

  fread(buf, 1, fsize, file);

I'm really in doubt, because malloc should alloc like fsize * sizeof(size_t) large space for me, but when I tried to visit like buf + 8*fsize, and I'm out of bounds.

though, the buf+fsize is in the correct place, end of file, and I just calculated the address, they all much!!! like malloc just returns me fsize * sizeof(char) large space for me.

So, where am I wrong, any help is appriciated.

Was it helpful?

Solution

Your code says malloc(fsize) but what you want is malloc(fsize * sizeof(size_t)). The malloc function takes the number of bytes to allocate. It has no way to know that you are going to use the memory to store size_t's.

Update: I may have misunderstood the question. I'll update this answer when the questioner answers the questions posed in my comment above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top