Home > Software engineering >  char pointer and static_cast in c code related to virtualalloc
char pointer and static_cast in c code related to virtualalloc

Time:12-17

I was searching for some code related to VirtualAlloc and came across this piece of code:

#include<windows.h>  
#include<iostream>
using namespace std; 

int main() {
size_t in_num_of_bytes,i;
cout<<"Please enter the number of bytes you want to allocate:";
cin>>in_num_of_bytes;                                      

LPVOID ptr = VirtualAlloc(NULL,in_num_of_bytes,MEM_RESERVE | MEM_COMMIT,PAGE_READWRITE); //reserving and commiting memory

if(ptr){
    char* char_ptr = static_cast<char*>(ptr);
    for(i=0;i<in_num_of_bytes;i  ){ //write to memory
        char_ptr[i] = 'a';
    }

    for(i=0;i<in_num_of_bytes;i  ){ //print memory contents
        cout<<char_ptr[i];
    }

    VirtualFree(ptr, 0, MEM_RELEASE); //releasing memory    
}else{
    cout<<"[ERROR]:Could not allocate "<<in_num_of_bytes<<" bytes of memory"<<endl; 
}

return 0;
}

This is a piece of code that I am trying to understand. However, I am confused about the following line:

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

I am not sure as to why this line is needed. And what does it do?

CodePudding user response:

Simpler example:

void* allocate_some_stuff(){
    return new char[42];
}

int main()
{
    void* ptr = allocate_some_stuff();
    char* cptr = ptr;
}

Because C does not allow implicit conversion from void* to char* it causes the error:

<source>:9:18: error: invalid conversion from 'void*' to 'char*' [-fpermissive]
    9 |     char* cptr = ptr;
      |                  ^~~
      |                  |
      |                  void*

But is fine when you explicitly cast:

int main()
{
    void* ptr = allocate_some_stuff();
    char* cptr = static_cast<char*>(ptr);
}

void* can point (almost) anywhere and casting to char* is generally ok (char is an exception with respect to that). When dealing with void* the type system is bypassed and to some large extend it is up to you to know what that pointer actually points to or what it can be used for.

  • Related