Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct use of Stat on C

Tags:

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);
like image 347
necronet Avatar asked Jun 29 '10 07:06

necronet


2 Answers

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);
like image 163
Puppe Avatar answered Sep 19 '22 03:09

Puppe


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.

like image 32
Muhammad Anjum Kaiser Avatar answered Sep 22 '22 03:09

Muhammad Anjum Kaiser