Question

For a program that I'm writing, it is useful for me to calculate file sizes, which I calculate by using iostream's tellg and seekg functions, but this leads to a warning by -Wstack-protector. The following code reproduces the "problem":

#include <iostream>

std::streamsize get_file_size(std::ifstream& ifs) { // line 12 (in warning, below)
  const std::streamsize start = ifs.tellg();
  ifs.seekg(0,std::ios::end);
  const std::streamsize end = ifs.tellg();
  ifs.seekg(start);
  return (end-start);
}

g++ (flags: -fstack-protector -Wstack-protector, compiler version: 4.4.3 (Ubuntu 4.4.3-4ubuntu5), system: Ubuntu 10.04 x86_64) gives the warning:

f.cc: In function ‘std::streamsize get_file_size(std::ifstream&)’:
f.cc:12: warning: not protecting function: no buffer at least 8 bytes long

(I get the same results when I use GCC 4.5.2, downloaded and compiled from GNU directly.)

Is this expected from how stack smashing protection works (in general or by GCC) and/or how ifstream and seekg/tellg work? If so, can't this warning be ignored or is there something better that I can do?

Edit:

Actually, some of the code above is redundant. Just to clarify what's going on:

#include <iostream>

void f1(std::ifstream& ifs) { // line 6
    ifs.tellg();
}

void f2(std::ifstream& ifs) { // line 10
    // call seekg(std::streampos)
    ifs.seekg(0);
}

void f3(std::ifstream& ifs) {
    // call seekg(std::streamoff, std::ios_base::seekdir)
    ifs.seekg(0,std::ios::beg);
}

leads to g++ (same specs as above) warning:

main.cc: In function ‘void f1(std::ifstream&)’:
main.cc:6: warning: not protecting function: no buffer at least 8 bytes long
main.cc: In function ‘void f2(std::ifstream&)’:
main.cc:10: warning: not protecting function: no buffer at least 8 bytes long

Interestingly, f3 does not trigger a warning.

Was it helpful?

Solution

You might wan't to see this.

And the general advice is you really shouldn't care, especially in your case, when you don't allocate any internal buffers that can be used to perform buffer overflow attack.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top