3

Im new to C Programming and the Windows API im getting "Run-Time Check Failure #2 - Stack around the variable 'pMyStringAdress' was corrupted." after compilation in Visual Studio

Thats my code:

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

char MyStrings[] = "ich bin ein text";

int main() {    
    SIZE_T SizeMyStrings = sizeof(MyStrings);

    PVOID pMyStringAdress = VirtualAlloc(
        NULL,
        SizeMyStrings,
        MEM_COMMIT | MEM_RESERVE,
        PAGE_READWRITE
    );

    if (pMyStringAdress == NULL) {
        printf("VirtualAlloc fehlgeschlagen mit fehlercode %d", GetLastError());
    }
    else {
        printf("Speicher erfolgreich allokiert sitzt bei: %p\n", &pMyStringAdress);
    }

    printf("Probiere in den Speicher zu schreiben.");
    memcpy(&pMyStringAdress, MyStrings, SizeMyStrings);
    return 0;
}
New contributor
reiner is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

2 Answers 2

6

You're copying into the wrong address.

pMyStringAdress is a pointer that holds the heap address returned by VirtualAlloc.

But you used &pMyStringAdress (the address of the pointer variable on the stack) both when printing and in memcpy. That writes past the pointer variable itself and trashes the stack, hence the message "Run-Time Check Failure #2 … stack … was corrupted."

Fixes

  • Use pMyStringAdress (no &) when printing and copying.
  • Free with VirtualFree when done.
  • Minor: use the right printf specifiers.
Sign up to request clarification or add additional context in comments.

1 Comment

3

This is because of Windows' dysfunctional type system. PVOID is similar to void* and so when you do memcpy(&pMyStringAdress you get a void** which is wrong. Drop the & during memcpy.

1 Comment

This answer is short but this reply contains a very clear answer. Good!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.