Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

c++ - Acessing memory referenced by void pointer

I am getting my head around void pointers in C++ and as an exercise have written the following code:

void* routine(void* number){

    int n = (int)number;
    int* np = (int*)number;

    cout<<"void pointer: "<<number<<endl; 
    cout<<"casted int pointer: "<<np<<endl; 
    cout<<"int pointer content: "<<*np<<endl; 


    return (void*)NULL;
}

int  main(){
    int num = 1;
    routine((void*)num);
}

This breaks in runtime as the pointer np, casted from void* to int* is dereferenced.

I attempt to pass the argument number as a void pointer and dereference its value inside the function. Arithmetic on void pointers are illegal, therefore what I try to do is cast the pointer to an int* and attempt to dereference this casted copy.

I somewhat expect this not to work, but if that were the case I would also expect some sort of compiler error as is the case when this attempt is made without the int* cast. The reason I sort of expect it to work is that the casted pointer retains the original void pointer address, meaning that after the cast it appears to be just a regular memory address, which I see no reason to be inaccessible by regular dereference. The n variable is a copy of the referenced value, but is just that - I cannot change the actual value in the memory address.

Is this possible with a void pointer? What am I missing?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The usual &num will do.

routine(&num);

Any object pointer implicitly converts to void*. On the callback function you'll have to convert it back to the correct pointer type (use static_cast not C-style cast, that will prevent you from accidentally mixing up pointers containing addresses with integer values that are not memory addresses).

void* routine( void* user_ptr )
{
    int* np = static_cast<int*>(user_ptr);

Other pointers which aren't object pointers won't implicitly convert to void*, including function pointers and pointer-to-members. Adding a cast will force the compiler to do the wrong thing and be quiet about it, but (apart from the return value of dlsym() or its Windows equivalent GetProcAddress()) it isn't safe to mix void* with these other pointer varieties anyway.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...