-1

I am trying to write to a memory location allocated via VirtualAlloc(), and then read from it as a simple exercise. Below is my code:

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


int main(void) {
    //allocate memory
    WCHAR text[512];
    void* mem = VirtualAlloc(NULL,sizeof(WCHAR)*512,MEM_RESERVE| MEM_COMMIT,PAGE_READWRITE);
    if (mem == NULL) {
        printf("Memory allocation failed\n");
        return 0;
    }
    //query user to store text into memory
    printf("Mem address: 0x%p\nEnter text to copy to pointer mem: ",mem);
    scanf_s("%S",text,_countof(text));
    wcscpy_s((WCHAR*)mem, sizeof(text)/sizeof(WCHAR), text);
    
    //read text from memory location
    WCHAR readText[512];
    wcscpy_s(readText,_countof(readText),(WCHAR *)mem);
    wprintf(L"What was in mem: %ls",readText);
    VirtualFree(mem, 0, MEM_RELEASE);  // Release the allocated memory
    return EXIT_SUCCESS;
}

However, when I type in Hello world! as input, it only outputs Hello instead of what was input. Below is the console output:

Mem address: 0x000001EB5E1A0000
Enter text to copy to pointer mem: hello world!
What was in mem: hello
user2494337
  • 47
  • 1
  • 5
  • OT: `sizeof(text)/sizeof(WCHAR)` will always be `512`, which is the size of the array. So why the calculation instead of hard-coding `512`? Or use a macro for the size? Or use `_countof` for that as well? – Some programmer dude Aug 08 '23 at 08:28
  • 3
    As for your problem, all `scanf` family functions reads strings as *space delimited words*. You should have checked the input and that would have been obvious. The rest of the program works as intended. – Some programmer dude Aug 08 '23 at 08:29
  • 4
    So the lesson for today is: [How to debug your programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). That is a *crucial* skill, that you really need to learn if you're serious about programming in any way. – Some programmer dude Aug 08 '23 at 08:30
  • For anybody reading, scanf() can't take space-delimited strings without specifying. You have to use fgetws() to read a sentence without a newline. Here is the code that I used to fix the error: ```fgetws(text,512,stdin);``` – user2494337 Aug 08 '23 at 08:48
  • 1
    *"You have to use fgetws() to read a sentence without a newline."* Actually, just like `fgets`, `fgetws` will store the newline in the buffer unless the end of stream is reached before the newline is read, or unless one less than the buffer length characters have been read without reading a newline. – Ian Abbott Aug 08 '23 at 09:25

1 Answers1

1

scanf_s Reads formatted data, delimited by whitespace characters by default, from the standard input stream.

To read strings not delimited by whitespace characters, a set of characters in brackets ([ ]) can be substituted for the s (string) type character.

For example wscanf_s(L"%[^\n]", text, _countof(text));

Also see https://stackoverflow.com/a/13728449/15511041.

YangXiaoPo-MSFT
  • 1,589
  • 1
  • 4
  • 22