If you have a function in C that takes ownership of whatever is passed into it, such as a function that adds a struct
to a vector buffer by-value, and this struct value contains a member pointer to a character array (a string).
During the buffer's cleanup routine, it should release the strings that it owns, but what if some strings are allocated at runtime, but others are allocated at compiletime using a string literal.
There is no safe and standard (non-proprietary) way to detect if a char*
points to read-only memory, so what is this hypothetical freeVector
function to do with a pointer to a char buffer?
struct Element {
int id;
char* name;
}
struct Vector {
size_t maxIndex;
size_t length;
struct Element buffer[];
}
void addToVector(struct Vector* vector, struct Element element) {
// lazy-reallocation logic here if maxIndex => length
vector->buffer[ vector->maxIndex++ ] = element; // by-value copy
}
void freeVector(struct Vector* vector) {
for(size_t i = 0; i < vector->maxIndex; i++ ) {
free( vector->buffer[ i ].name ); // segfault/AV if name is a literal
}
}