Re: When Immutability and Nullability Meet: Exploring Mutable Objects in C

Liste des GroupesRevenir à cl c  
Sujet : Re: When Immutability and Nullability Meet: Exploring Mutable Objects in C
De : thiago.adams (at) *nospam* gmail.com (Thiago Adams)
Groupes : comp.lang.c
Date : 18. Sep 2024, 22:20:46
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vcfcmv$2mgp$1@dont-email.me>
References : 1
User-Agent : Mozilla Thunderbird
On 17/09/2024 18:27, Thiago Adams wrote:
 I found some use cases where we may want disable const and _not_null (if C had this qualifier) at same time. Kind of "anti-qualifier".
I think
I think my post might not have any replies because it's too long. So here's a shorter version.
Consider this sample: It has a error and a warning
#include <stdlib.h>
#include <string.h>
struct person {
   const char* const name;
};
struct person * make(const char* name)
{
   struct person * p = malloc(sizeof *p);
   if (p == 0) return 0;
   p->name = strdup(name);  //error read-only
   return p;
}
void person_delete(struct person* p) {
     free(p->name); //warning
}
int main()
{
   const struct person * p = make("a");
   if (p){
      person_delete(p); //warning
   }
   return 0;
}
My suggestion is remove the error and warning by adding a new qualifier mutable
mutable struct person * p = malloc(sizeof *p);
That allows p->name to be changed and person_delete to be called with no warnings.
void person_delete(mutable struct person* p) {
     free(p->name); //ok
}
https://godbolt.org/z/5Yo63ab1Y

Date Sujet#  Auteur
17 Sep23:27 * When Immutability and Nullability Meet: Exploring Mutable Objects in C2Thiago Adams
18 Sep22:20 `- Re: When Immutability and Nullability Meet: Exploring Mutable Objects in C1Thiago Adams

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal