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
:
free(buf);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With