Let's assume that, we have a C API exposed by a C++ library where the C client queries a value by passing a void pointer and a key.
bool GetValue(const char* key, void* val) {
if(val != NULL) {
// find the value using the key with some logic of library
// lets assume found value is a int
int foundValue = 34;
*(int*)val = foundValue;
return true; // or false if key not found
}
return false;
}
The C client and the C++ library developers have an agreement about the size of values associated with keys.
Let's assume the C++ library only has int
and long long int
, and the C client also knows it.
So the C client is expected to behave as follows when the value associated with "some_key"
is an int
:
int valueHolder;
if(GetValue("some_key",&valueHolder)) {
// do something with valueHolder
}
But the C client can cause stack memory corruption by providing pointer which points to less space. For example, if the C client provides a pointer which points to an unsigned char
and the value written by the C++ library is int
, stack memory corruption can happen.
So the C client should take proper action to avoid such a situation. My question is, how the C++ library can handle such memory corruption/crash situation and be robust to crash or memory corruption? (a small note: a template or function overload is not an option for me because C++ library can not expose such feature to a C client).