-2

My code looks like this:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    FILE* file;
    file = fopen("file.txt", "w+");
    char *tab;
    char *tab2;
    cout << "Input: " << endl;
    cin >> tab;
    fprintf(file, "%s", tab);
    rewind(file);
    fscanf(file, "%s", tab2);
    printf("%s", tab2);
    fclose(file);
}

So saving to file is working, but while I want to read from file to *tab2 it doesn't work and program instantly crashes. Any help with this?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Coonvert
  • 3
  • 1
  • You are operating on uninitialized pointers, that's _undefined behavior_. – πάντα ῥεῖ Mar 16 '22 at 17:53
  • It's frankly a miracle the first half works. `tab` and `tab2` point to, erm, whatever they feel like pointing to. Could be valid memory, could be NULL, could be your operating system. See [Undefined behavior](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior). – Silvio Mayolo Mar 16 '22 at 17:53

1 Answers1

1
char *tab;
char *tab2;

These lines just declare pointers to unspecified addresses. When you try reading or writing through those pointers, you are invoking undefined behavior. You might get a crash, or you might not. Or you might just corrupt memory.

You need to allocate memory buffers and then make those pointers point to those buffers. But, because you are using C++, not just plain C, just use C++ ways of working with strings, reading files, etc. There are std::string and std::ifstream classes for this purpose.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Paul
  • 13,042
  • 3
  • 41
  • 59