tags:

views:

118

answers:

5

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);
+7  A: 

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.

Puppe
(But don't forget to `free()` it afterwards.)
Amber
+1  A: 

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.

Didier Trosset
+1  A: 

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) * 1);

stat(fd, buf);
int size = buf->st_size;
printf("%d",size);

free(buf);

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

Anjum Kaiser
A: 

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.

Lajos Arpad
A: 

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.

Kumar Alok