Question

I have the following input file:

1 100000 hajs ssaa 25
2 150000 sdsd Assso 22
...

And the following program:

#define _UNICODE
#define UNICODE

#define _CRT_SECURE_NO_WARNINGS

#include <Windows.h>
#include <tchar.h>
#include <stdio.h>
#include <stdlib.h>


#define MAX_CHARS       30

typedef struct student
{
    WORD identifier;
    DWORD registerNumber;
    TCHAR surname[MAX_CHARS + 1];
    TCHAR name[MAX_CHARS + 1];
    WORD mark;

} student_t, *student_ptr;


int _tmain(DWORD argc, LPTSTR argv[])
{
    FILE* fileIn;
    errno_t error;
    student_t student;

#ifdef UNICODE
    error = _wfopen_s(&fileIn, argv[1], L"r");
#else
    error = fopen_s(&fileIn, argv[1], "r");
#endif

    if (error)
    {
        _ftprintf(stderr, _T("Unable to open %s\n"), argv[1]);
        exit(EXIT_FAILURE);
    }

    while (_ftscanf_s(fileIn, _T("%hu %lu %s %s %hu"), &student.identifier, &student.registerNumber, 
        student.surname, student.name, &student.mark) != EOF)
    {

    }

    fclose(fileIn);

    return 0;
}

Now, if I use _ftscanf_s I have the following exception:

First-chance exception at 0x53871CA4 (msvcr110d.dll) in vsproj.exe: 0xC0000005: Access violation writing location 0x002F0000.

While if I use _ftscanf (the unsafe version) the program runs without errors. Why?

Was it helpful?

Solution

You have to specify the length arguments that are needed with %s. Please, try to use the _countof macro:

while (_ftscanf_s(fileIn, _T("%hu %lu %s %s %hu"), &student.identifier, &student.registerNumber, 
        student.surname, _countof(student.surname), student.name, _countof(student.name), &student.mark) != EOF)
{
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top