Cast abuse



Just pulled the latest balsa from CVS and got problems compiling 
address-book-ldap.c.  The problem is that casts are used to abuse const 
strings. Fortunately gcc catches this nonsense and warns about it.

<rant>
As a general point, I feel that when programming in C, if a cast is used, 
something is wrong in the code.  All reasonable efforts should be made to 
rewrite the code avoiding the cast.  Use casts only as a last resort, after 
all a cast silences the compiler about potential coding errors.  Also remember 
that void pointers eliminate the need for a lot of casts, e.g. code like "ptr 
= (int *) malloc(..." is always unnecessary since malloc returns a void *.  
Just write "ptr = malloc(...".  The same goes for comparisons with void 
pointers, forget the cast.
</rant>

The following trivial patch corrects the problem and allows the compiler to 
generate more robust code (because it knows to check that *in is never 
assigned).

Brian Stafford


Index: libbalsa/address-book-ldap.c
===================================================================
RCS file: /cvs/gnome/balsa/libbalsa/address-book-ldap.c,v
retrieving revision 1.13
diff -u -r1.13 address-book-ldap.c
--- libbalsa/address-book-ldap.c        2001/11/13 23:05:12     1.13
+++ libbalsa/address-book-ldap.c        2001/11/19 11:02:24
@@ -293,7 +293,7 @@
   static gchar *ldap_get_string(const gchar *ldap_string)
  {
-    char *in=(char *)ldap_string;
+    const char *in=ldap_string;
      size_t len=strlen(in), outlen=len;
      char *native_string=calloc(outlen+1, sizeof(char)), *out=native_string;
      iconv_t conv=iconv_open(BALSA_CODESET, LDAP_CODESET);
@@ -315,7 +315,7 @@
   static gchar *ldap_set_string(const gchar *native_string)
  {
-    char *in=(char *)native_string;
+    const char *in=native_string;
      size_t len=strlen(in), outlen=2*len; /* Worst case */
      char *ldap_string=calloc(outlen+1, sizeof(char)), *out=ldap_string;
      iconv_t conv=iconv_open(LDAP_CODESET, BALSA_CODESET);



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]