Using void pointers: 0xC0000005: Access violation reading location

2

I'm just experimenting with void pointers, I wanted to use them on C-type strings. It seems that this line of code throws the exception, but I don't know why:

printf("My name is %s", *((char*)ptr));

Here is the entire code:

int main()
{
    char prenume[] = "Alexandru";
    char* name = prenume;
    int age = 33;
    float height = 1.81;

    void* ptr;
    ptr = name;
    printf("My name is %s", *((char*)ptr));
    ptr = &age;
    printf("\nAge:%d", *((int*)ptr));
    ptr = &height;
    printf("\nHeight:%2.2f", *((float*)ptr));
    return 0;  
}

I am using MS Visual Studio

I would appreciate any answer...thanks!

c
void-pointers
asked on Stack Overflow Apr 9, 2020 by Alexandru Mitrofan • edited Apr 10, 2020 by Simson

2 Answers

1

Your code is inconsistent. You're getting the address of age and height and putting it into ptr, but you put name's value directly. Getting the address of a value adds a level of indirection (as in, using & on a char* gives you not char* but char**, the address of an address of a char).

Fixing your code to make it consistent:

void* ptr;
ptr = &name; //Added &.
printf("My name is %s", *((char**)ptr));
ptr = &age;
printf("\nAge:%d", *((int*)ptr));
ptr = &height;
printf("\nHeight:%2.2f", *((float*)ptr));

And it should now work. You can also rid yourself of that extra level of indirection (& and *) for less confusion.

answered on Stack Overflow Apr 9, 2020 by mid • edited Apr 9, 2020 by mid
1

I think you want to use the void * ptr as a general pointer to any data types. The problem in your code is as below.

int main()
{
    char prenume[] = "Alexandru";
    char* name = prenume;
    int age = 33;
    float height = 1.81; //<=== this line will cause a truncation warning at compile time

    void* ptr;
    ptr = name;
    printf("My name is %s", *((char*)ptr)); // <======= this line will cause access violation error at runtime
    ptr = &age;
    printf("\nAge:%d", *((int*)ptr));
    ptr = &height;
    printf("\nHeight:%2.2f", *((float*)ptr));
    return 0;  
}

You should use ((char*)ptr) (remove the leading *). This expression resolve to the address of the A. Because %s expects the start address of a string.

If you use *((char*)ptr), it resolves to the char value A. The ASCII value of A is 0x41, which is not an address you can usually access. And below debug message shows that it is the address 0x41 is causing access violation.

enter image description here

After making above changes, your code can run like below:

enter image description here

And btw, C is a dangerous beauty...

answered on Stack Overflow Apr 10, 2020 by smwikipedia • edited Apr 10, 2020 by smwikipedia

User contributions licensed under CC BY-SA 3.0