[CLN-list] how to assign cl_I type to structure number

Bruno Haible bruno at clisp.org
Mon Feb 6 13:23:54 CET 2006


Hi,

mahesh ram wrote:
>  i have faced the following problem:
>  cl_I val=10;
>  struct node
>  { cl_I data;
>    struct node * link;
>  };
>  struct node * start=NULL;
>  start = (struct node *) malloc(sizeof(struct node));
>  start->data = value; // error in this line;

That's because the memory of start->data is uninitialized.
You have two ways to fix that:
1. Initialize the memory from the beginning by use of 'new' instead of 'malloc'
   (and then of course use 'delete' instead of 'free'):
     start = new node();
     start->data = value;
2. Keep the memory uninitialized first, and initialize it later:
     start = (struct node *) malloc(sizeof(struct node));
     new (&start->data) cl_I(value);
   In this case also don't forget to call the destructor of 'data' before
   calling free(), otherwise you have a nice memory leak.
     start->data.~data();
     free(start);

Bruno



More information about the CLN-list mailing list