c++stringwinapimemoryvirtualalloc

string input not printed correctly on the screen


I am trying to read in a string from the user input and then print it on screen. However, when the string is printed on the console, it is kind of gibberish. The funny thing is that it works in Visual Studio and not in CodeBlocks.

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

int main() {
    int i, num_bytes;
    char sentence[] = "";
    std::cout << "Please enter your name: ";
    //fgets(sentence, 100, stdin);
    //scanf("%[^\n]%*c", sentence);
    //scanf("%[^\n]", sentence);
    std::cin >> sentence;
    num_bytes = strlen(sentence);

    LPVOID ptr = VirtualAlloc(NULL, num_bytes, MEM_RESERVE, PAGE_READWRITE);
    ptr = VirtualAlloc(ptr, num_bytes, MEM_COMMIT, PAGE_READWRITE);

    if (ptr) {
        char* char_ptr = static_cast<char*>(ptr);

        for (i = 0; i < num_bytes; i++) {
            char_ptr[i] = sentence[i];
        }

        std::cout << "Allocated Memory Address: " << (void *)ptr << std::endl;

        std::cout << "Press Enter to print out the characters.\n";
        getchar();

        for (i = 0; i < num_bytes; i++) {
            std::cout << char_ptr[i];
        }

        std::cout << "\nPress Enter to clear memory." << std::endl;
        getchar();

        VirtualFree(ptr, 0, MEM_RELEASE);
    } else {
        std::cout << "Could not allocate " << num_bytes << " of memory." << std::endl;
    }

    std::cout << "\nPress Enter to continue." << std::endl;
    getchar();
}

Solution

  • You should explicitly specify memory size for string. That code:

    char sentence[] = "";
    

    declares sentence with max size is 0 (+1 zero symbol). Of course, you write more data into not-your memory. Try this:

    char sentence[200] = "";