0

I use the following code to find the disk usage of my /

int main()
{
    struct statfs *stat;
    statfs64("/tmp",stat);
    perror("");
    printf("%lu \n",stat->f_bfree*stat->f_bsize);
    return 0;
}

The perror keeps on printing "Bad Address" and a random number for size.

Bad address

3264987920

PS:I tried sudo ./a.out,statfs("a.out",stat)

What may be the issue?

rjv
  • 6,058
  • 5
  • 27
  • 49

2 Answers2

4

You've declared a pointer to a statfs struct but don't actually have space allocated for such a struct. The pointer points off into nowhereland. It's uninitialized, it doesn't point anywhere legal.

struct statfs stat;

if (statfs64("/tmp", &stat) == -1) {
    perror("statfs64");
}
else {
    printf("%lu\n", stat.f_bfree * stat.f_bsize);
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Thanks:) that worked :)I would like to add that `statfs64` may trigger a segmentation fault,which can be removed by using `statfs` instead – rjv Apr 17 '13 at 01:52
  • @RajeevS Right. `statfs()` and `struct statfs` should be used together, and `statfs64()` and `struct statfs64` as well. The use of the latter is deprecated; they are used instead of `statfs()` if the correct symbols are defined. – glglgl Apr 17 '13 at 10:03
0

You have used statfs *stat with no memory allocation hence wild pointer usage it may point to anywhere ( illegal memory address) Either Initialise it with valid memory or use variable and pass its reference.

anshul garg
  • 473
  • 3
  • 7
  • You are saying the same as [John said 7 1/2 hours before you...](http://stackoverflow.com/a/16050052/296974) – glglgl Apr 17 '13 at 10:03