|
|
|
|
|
by menaerus
765 days ago
|
|
> gcc will compile this code and advance the pointer address by 1 byte. Yes, it's not standard conformant. https://godbolt.org/z/cjoYvjxGq <source>: In function 'void foo(int)':
<source>:4:28: warning: pointer of type 'void *' used in arithmetic [-Wpointer-arith]
4 | int * p = malloc(size) + 1;
| ~~~~~~~~~~~~~^~~
<source>:4:28: error: invalid conversion from 'void*' to 'int*' [-fpermissive]
4 | int \* p = malloc(size) + 1;
| ~~~~~~~~~~~~~^~~
| |
| void\*
Compiler returned: 1
|
|
Second, the error about implicit conversion from void-pointer to typed-pointer is in C++ only -- not in C, where you won't even get a warning. The error happens because you didn't cast the void pointer to the target type and doesn't have to do anything with the fact that gcc _does_ let you (as a GCC extension) do arithmetic on void pointers.
If you remove the "+ 1" you'll still see the same error in C++. In C++, change the target pointer to a void pointer:
or, alternatively, cast the RHS expression properly (doesn't matter with "+ 1" or without) and the error will go away.