'Problem with fscanf function while using *char

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?

c++


Solution 1:[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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Remy Lebeau