Consider the following code:
struct ns_test{
char *str;
};
struct ns_test *ns_test_alloc(char *str){
struct ns_test *nt = malloc(sizeof(*nt));
nt->str = str;
return nt;
}
const char *ns_test_get_str(struct ns_test *tst){
return tst->str;
}
void ns_test_release(struct ns_test* tst){
free(tst);
}
void ns_test_set_char(struct ns_test *tst, size_t i, char c){
tst->str[i] = c;
}
int main(void){
char arr[] = "1234567890";
struct ns_test *ns_test_ptr = ns_test_alloc(arr);
const char *str = ns_test_get_str(ns_test_ptr);
printf("%s\n", str); //1234567890
ns_test_set_char(ns_test_ptr, 4, 'a');
printf("%s\n", str); //1234a67890
}
The question is: Is the behavior of the code undefined?
I think it is.
The Standard specifies at 6.7.3(p6):
If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.
So to avoid this sort of UB we need const char *ns_test_get_str(struct ns_test *tst) to copy the char *str instead. But the main point was to avoid the copying and restrict the modification to the only void ns_test_set_char(struct ns_test *tst, size_t i, char c) which may do some sanity checks or something else prior.
char arr[]in themainfunction is notmalloced.char arr[]isn't really important here. It's yourns_test_ptr->strthat is being aliased.ns_test_ptr->strreffers to the object with declared typechar[]aschar arr[]was declared. So there is no problem.