1

I'm currently writing a little library of secure char and secure list (just .c/.h files that I will add to future projects) and something is bothering me, I know that some of you will think it is subjective but I think there is a "real" best way to do it. I've searched but there is nothing that give me a close answer. Here is a sample of my code.

The struct and functions used :

typedef struct _secure_list
{
    cookie secret; // MUST be set to Cookie 
    secure_char * schar;
    struct _secure_list * next;
} secure_list;

typedef struct _secure_char
{
    int length; // number of characters in the string
    char    * str;  // the string (no \0 byte at the end of the string)
} secure_char;


/**
 * Create a secure list with schar
 * Initialize Cookie on first use
 **/
 ret_value createSecureList( secure_char * scIn, secure_list ** slist )

I think there is two possible ways to write the createSecureList function :

 // FIRST WAY
 ret_value createSecureList( secure_char * scIn, secure_list ** slist )
 {
    (*slist) = NULL;
    (*slist) = (secure_list *) malloc( sizeof(secure_list) );

    // we copy the secure_char so it can be freed in the caller
    createSecureChar("",&((*slist)->schar));
    concat2SecureChar(&((*slist)->schar), scIn);
    ...
 }

 // SECOND WAY
 ret_value createSecureList( secure_char * scIn, secure_list ** slist )
 {
    (*slist) = NULL;
    (*slist) = (secure_list *) malloc( sizeof(secure_list) );
    (*slist)->schar = scIn; 
    ...
 }

In my main() I have :

void main()
{
   secure_list * slist_Test;
   secure_char * schar_Test;
   ....
   createSecureChar("test test",&schar_test); 
   createSecureList(schar_Test,&slist_Test); 
   ....
}

My problem is that despite the fact the second way is easier to code and understand, the secure list which is a linked list will point to the same memory space as schar_Test, so if we free one of them, we free both. The first way basically create a copy of schar_Test so it can be freed in the calling function.

Can someone tell me which is the "right" way ?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
  • 2
    Either could be right, it depends on your needs. It's the difference between a [deep copy and shallow copy](http://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy). – Adam Rosenfield Jan 07 '14 at 19:26
  • `slist * slist_Test; schar * schar_Test;`: what are `slist`and `schar`? – alk Jan 07 '14 at 19:29
  • @alk : Sorry I wrote it too rapidly "slist" is in fact a `secure_list` and schar is another struct containing a `char * str` (without '\0') and `int length`. – George Abitbull Jan 07 '14 at 19:36

0 Answers0