Home > Back-end >  Safe to change char* function parameter to char const* in shared library function?
Safe to change char* function parameter to char const* in shared library function?

Time:11-09

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:

  1. Pointer to char parameter, passing pointer to char
  2. Pointer to char parameter, passing pointer to const char
  3. Pointer to const char parameter, passing pointer to char
  4. Pointer to const char parameter, passing pointer to const 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.)

  •  Tags:  
  • c
  • Related