Home > Software design >  Unhandled exception at 0x00007FFB158DA726 (ucrtbase.dll) in AI.exe: 0xC0000005: Access violation wri
Unhandled exception at 0x00007FFB158DA726 (ucrtbase.dll) in AI.exe: 0xC0000005: Access violation wri

Time:01-03

When I run the code here happen after scanf("%[^\n]", order); Full code:

#define _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_DEPRECATE  
#define _CRT_NONSTDC_NO_DEPRECATE

#include <stdio.h>
#include <Windows.h>
#include "Colors.h"
#include <string>
#include "Functions.h"
#include <stdbool.h>
using namespace std;

int main() {
    //vars
    char* order = "";
    int WinH;
    int WinW;
    bool error = false;
    GetDesktopResolution(WinH, WinW);
    // end vars
    //funcs
    //DelayedStart();
    //end funcs
    Sleep(1500);
    system("CLS");
    Sleep(250);
    SetConsoleTitle(L"AI APP   -   Main");
    printf("Hello,\nHow can I help you\n>>");
    F_GREEN;
    scanf("%[^\n]", order); //error here
    F_B_Defalt;
    
    if (order == "open youtube") {
        ShellExecute(0, 0, L"http://www.youtube.com", 0, 0, SW_SHOW);
    }
    else
    {
        printf("%s\n", order);
        puts("Whoops");
    }
    system("PAUSE");
}

Visual Studio 2022 V17.4

CodePudding user response:

You are scanning into a string literal(""), which provokes undefined behaviour!

Actually you should have gotten a compiler warning, because of assigning this string literal, which has type char const/*!!!*/ *, to a variable of char /*non-const!*/ *. Some compilers do allow this for reasons of compatibility to C. Some of these (e.g. GCC) allow to enhance this warning to a compilation error, not sure if MSVC does so, too, but if it does, you should do so!

Additionally this string literal only contains room for one single character, so (if it was possible at all...) you only could read an empty string into (containing the terminating null character), otherwise you'll provoke undefined behaviour again for writing beyond array bounds.

Either of these two kinds of undefined behaviour might have provoked the segmentation fault.

To fix provide a writable character buffer long enough to hold expected input:

char order[128];
// ...
scanf("7[^\n]", order);

Note how in above format string a maximum length for reading characters is specified, this needs to be, though, one less than the buffer size as the scan operation will yet append the terminating null character.

Note, too, how order decays to a pointer to its first element implicitly, so you do not need to take the address of – actually this would even be wrong and provoke undefined behaviour for providing non-matching pointer types (char(*)[128] vs. char*) to the format specifier (even though the address would be the same).

  •  Tags:  
  • c
  • Related