Bug in code. c++. ifstream.



  • Why does this code fall with Segmentation fault?

    #include <fstream>
    #include <iostream>
    

    void func(std::ifstream &f, std::string &key_len_str) {
    char *c;
    f.read(c, 1);
    key_len_str += (std::string) c;
    }

    int main() {
    std::ifstream f("f.txt", std::ios_base::binary);
    std::string s = "";
    func(f, s);
    func(f, s);
    func(f, s);
    std::cout << s << std::endl;
    }



  • Baga is here.

    char *c;
    f.read(c, 1);
    

    You're setting up an index for type char, but you you don't memorize. How to fix it.

    Good one.

    char c;
    f.read(&c, 1);
    

    Worse, worse (option is not recommended for use in real programmes, except if necessary for a depressed teacher).

    char * c = new char;
    f.read(&c,1);
    delete c;
    

Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2