If I change an existing function in a shared library
int some_function(char* some_string)
to
int some_function(char const* some_string)
Is this a safe change? Will applications that use the library need re-linking or can I drop in a replacement .so file? The function body is not modified. The function does not modify some_string
.
CodePudding user response:
There are four possible combinations:
- Pointer to
char
parameter, passing pointer tochar
- Pointer to
char
parameter, passing pointer toconst char
- Pointer to
const char
parameter, passing pointer tochar
- Pointer to
const char
parameter, passing pointer toconst char
This will break code only in case 2, and if the called function tries to write via the pointer*.
All other combinations are fine.
Actually, with the const
at the parameter you put a constraint on the called function, not on the caller. With the const
you assure the caller that the object at the pointer will not be modified.
*) Any serious compiler shall warn you if you do this. And the resulting program can crash on systems that take memory protection seriously. (For example, Win95 did not, and when we switched to Win2K and tried to qsort()
a const
array, we had a hard time to find the reason.)