Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I trust the behavior of C++ functions that declare const?

This is a C++ disaster, check out this code sample:

#include <iostream>

void func(const int* shouldnotChange)
{
    int* canChange = (int*) shouldnotChange;
    *canChange += 2;
    return;
}


int main() {
    int i = 5;
    func(&i);
    std::cout << i;
    return 0;
}

The output was 7!

So, how can we make sure of the behavior of C++ functions, if it was able to change a supposed-to-be-constant parameter!?

EDIT: I am not asking how can I make sure that my code is working as expected, rather I am wondering how to believe that someone else's function (for instance some function in some dll library) isn't going to change a parameter or posses some behavior...

like image 461
Lawand Avatar asked Nov 26 '22 21:11

Lawand


1 Answers

Based on your edit, your question is "how can I trust 3rd party code not to be stupid?"

The short answer is "you can't." If you don't have access to the source, or don't have time to inspect it, you can only trust the author to have written sane code. In your example, the author of the function declaration specifically claims that the code will not change the contents of the pointer by using the const keyword. You can either trust that claim, or not. There are ways of testing this, as suggested by others, but if you need to test large amounts of code, it will be very labour intensive. Perhaps moreso than reading the code.

If you are working on a team and you have a team member writing stuff like this, then you can talk to them about it and explain why it is bad.

like image 147
mch Avatar answered Dec 31 '22 09:12

mch