Re: Type Safety cleanup diff



Your comments are are mostly in line with current practice, however,
my beef is with the assertion that something like the following leads
to less safe code:

DialogCBData *cb_data = (DialogCBData *)g_malloc0 (sizeof (DialogCBData));

The problem here is that the above code almost never occurs in the
real world (and certainly not in the Network Manager code). More often
than not, the declaration is separated from the assignment by at least
several lines, and often by more than a page. Thus the additional
verbage can be useful to the maintainer.

As for the C++ promotion rules for void pointers, well, they are there
kind of like how goto is still in C - for backwards compatibility, and
as such are generally considered bad form in regular programming.

As for the first issue you raise in you message about struct pointer
assignment, the attached code should disprove one of your assertions
(If I read your message right) about being able to assign a struct to
a struct pointer. The other examples are more or less disturbing,
depending on your perspective and should illustrate why the use of
void* as a magic type intermediary should be generally discouraged
with at least some verbage that prevents compilation should something
upstream change.

Evan

// Test of C99's void pointer default casts

#include <memory.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct Mystruct{
  int one;
  double two;
  char * three;
}Mystruct;
typedef struct Mystruct_v2{
  int one;
  double two;
  char * three;
}Mystruct_v2;


//The following two variants are from Robert's example
Mystruct *bar(){
  Mystruct *ms_ptr = malloc(sizeof(Mystruct));
  return ms_ptr;
}

Mystruct bar2(){
  Mystruct local_obj;
  return local_obj;
}
//This one's mine
Mystruct_v2 *bar3(){
  Mystruct_v2 *ms_ptr = malloc(sizeof(Mystruct));
  return ms_ptr;
}

int main(){
  Mystruct *st;
  char * generic_ch;
  Mystruct *foo;

  st = malloc(sizeof(Mystruct)); //void* to Mystruct* automatic cast (good code)
  generic_ch = (void*)st; // Void to mystruct automatic cast (good code)
  foo = bar(); //Same kind transmission (good code)
  foo = (Mystruct *)bar2(); //Attempt to call a struct a pointer generates a compiler error
  foo = (Mystruct *)bar3(); //Attempt to assign oldpointer to newer interface (compiles, tho bad idea because you now have some really confusing code)
  generic_ch = st; //Attempt to cast from two pointer types generates a compiler error
  st = generic_ch; //Attempt to cast from two pointer types generates a compiler error
}



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