A
A
Artyom_Kopan2021-09-28 22:29:48
C++ / C#
Artyom_Kopan, 2021-09-28 22:29:48

How to allocate dynamic memory for a text file in C?

I have a function:

FILE* openInputFile()
{
    printf("Enter the name of the input file: ");
    char* inputFileName;
    scanf("%s", &inputFileName);
    printf("%s", inputFileName);
    if (strstr(inputFileName, ".txt") == NULL)
        inputFileName = strcat(inputFileName, ".txt");
    printf("%s", inputFileName);
    FILE* inputFile = fopen(inputFileName, "r");
    return inputFile;
}

When you run it, the program crashes with the SIGSEGV error. Maybe you need to allocate dynamic memory for this file?
(Now I checked, it does not depend on the file size. What could be the error then?)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
CityCat4, 2021-09-29
@CityCat4

char* inputFileName;

It would be weird if it didn't crash, since inputFileName now points somewhere in space.
Dummies usually do this: and then they think - how is it that they broke me? who are smarter do this:
char inputFileName[256];
char *inputFileName;
inputFileName = (char *) calloc(256, 1);

(this, of course, is also not a star - you need to take into account the maximum allowable length of the path and file name, but it's much better)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question