Crumar
Crumar

Reputation: 132

const pointer contract only hot air?

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 :)

Upvotes: 0

Views: 118

Answers (2)

user3629249
user3629249

Reputation: 16540

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.

Upvotes: 0

P.P
P.P

Reputation: 121347

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.

Upvotes: 5

Related Questions