Tutorial :Correct use of Stat on C


Why does this work :

char *fd = "myfile.txt";  struct stat buf;              stat(fd, &buf);  int size = buf.st_size;    printf("%d",size);  

But this does not work:

char *fd = "myfile.txt";  struct stat *buf;              stat(fd, buf);  int size = buf->st_size;    printf("%d",size);  


The reason for it not working is that buf in the first example is allocated on the stack. In the Second example you only have a pointer to a struct stat, pointing to anywhere (probably pointing to address 0x0, i.e. a NULL pointer), you need to allocate memory for it like this:

buf = malloc(sizeof(struct stat));  

Then both examples should work. When using malloc(), always remember to use free() after you are finished with using the struct stat:



It is just a simple memory allocation problem.

char *fd = "myfile.txt";  struct stat *buf;              stat(fd, buf);  int size = buf->st_size;    printf("%d",size);  

The above code only declares a pointer, but in reality, there is no memory space allocated.

you should modify the code to look like this:

char *fd = "myfile.txt";  struct stat *buf;    buf = malloc(sizeof(struct stat));    stat(fd, buf);  int size = buf->st_size;  printf("%d",size);    free(buf);  

This will allocate the memory, and free after it is used.


In the second, you use a pointer pointing to you-dont-know-where. stat will by chance be able to correctly fill the values in the area pointed (your program could have terminated abruptly here). Then, as you have no idea on where this data is, you use it buf->st_size but maybe someone has used this memory area that you don't own.


It's a big difference between creating a structure or a pointer to a structure. The first code creates the structure, the second creates a pointer, to a not existing structure. Using malloc or calloc you can allocate memory and your structure will be initialized. After this you do whatever you want and at the moment when you don't need this structure anymore, you must use the free() function to free the allocated space.


You haven't allocated any memory for your pointer dude.

You should allocate memory to buf.

buf = malloc(sizeof(struct stat));  

now it will work.


This should fix your problem and another: file size can be either a 32 or 64-bit int. This example assumes a 64-bit machine.

#include <stat.h>  #include <errno.h>    char *file = "myfile.txt";  long long size; //st_size can be a 64-bit int.  struct stat *buf = malloc(sizeof(struct stat)); //allocates memory for stat structure.  errno = 0; //always set errno to zero first.    if(stat(file, buf) == 0)  {      size = buf->st_size;      printf("Size of \"%s\" is %lld bytes.\n", file, size);  }  else  {      perror(file);    //if stat fails, print a diagnostic.  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »