0
votes

I am currently working on a project including a somewhat generic linked list implementation using void pointers. Providing some utitily functions for these lists, I decided to make the identifying functions of elements only take (const void *). After adding the const keyword were necessary, I thought about how correct my code is now (if I implemented everything as it should be before).

As the compiler (GCC) didnt warn me, I decided to take a test. I compiled the following code with "gcc -g -Wall test.c" and received no warnings whatsover by GCC.

#include <stdio.h>
#include <stdlib.h>

void testf(const void *testp){
    *((int32_t *) testp) += 1;
}

void testf2(const int32_t *testp){
    *((int32_t *) testp) += 1;
}

int main(){
    int32_t testv = 0;
    printf("%i \n", testv);
    testf(&testv);
    printf("%i \n", testv);
    testf2(&testv);
    printf("%i \n", testv);
    return 0;
} 

The output is the following:

0 
1 
2 

I did not expect that C would actually crash by this, but I expected to receive a warning by the compiler. In this example im only casting, in my real functions I'm also assigning the const void pointers to a tmp variable.

Is this a bug?

Given how sophisticated todays compilers are, Id atleast expect a warning that Im casting a pointer to a non const pointer. If I change the cast and add the const keyword there too, GCC throws the usual error that I try to assign to a read only location

Am I supposed to rethink my trust to functions declaring const pointers? This is not what I understand as a contract :)

2
The casts silence the compiler. - alk
"I'm also assigning the const void pointers to a tmp variable" doing so without casting definitely would make the compiler yell out a warning. - alk
gcc will warn if casting away const if you enable the recommended warnings. However, if the compiler will not keep you from exploiting undefined behaviour. If you need that, use a different language. Ada might be a good candidate. - too honest for this site
What do you expect? A cast tells the compiler to shut up, so you are complaining that the compiler does exactly what you tell it? - too honest for this site

2 Answers

5
votes

Is this a bug?

No, it's not. By casting you are saying "I know what I am doing" to the compiler.

But GCC does have an option -Wcast-qual which would catch if a qualifier is casted away intentionally.

0
votes

I compiled the posted code using:

gcc -c -ggdb -Wall -Wextra -pedantic -std=c99 filename.c -o filename.o

(the following list is abbreviated for ease of reading)

error: 'int32_t' undeclared 

error: expected expression before ')' token
    *((int32_t *) testp) += 1;

warning: unused parameter 'testp'
    void testf(const void *testp){

with lots more warnings and errors regarding int32_t

Surely your compiler stated these same items.

BTW: The missing header file is stdint.h.