Search code examples
cpointersmemsetpointer-to-pointer

memset operation on double pointer


Question is relevant.

For the below representation,

  typedef struct List{

    void **array; // array of void*
    int lastItemPosition;
    int size;
  }List;

  #define INITIAL_LIST_SIZE 50

createList performs as shown below,

List *createList(List *list, Op opType){

  List *lptr = (List *)malloc(sizeof(List));

  if(opType == CREATE_NEW_LIST){

    lptr->array = malloc(INITIAL_LIST_SIZE*sizeof(void*));
    lptr->array = memset(lptr->array, NULL, INITIAL_LIST_SIZE*sizeof(void *));
    lptr->lastItemPosition = -1;
    lptr->size = INITIAL_LIST_SIZE;
}

Is memset performing valid operation on lptr->array?


Solution

  • In your code,

     memset(lptr->array, NULL, INITIAL_LIST_SIZE*sizeof(void *));
    

    is wrong, as the second argument is expected to be an int, you're passing a pointer. The conversion is a highly implementation defined behaviour, and in most of the cases, it would invoke UB.

    Related, quoting C11, chapter §7.19

    NULL
    which expands to an implementation-defined null pointer constant; [...]

    and, chapter §6.3.2.3

    An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.

    So, NULL is of pointer type which is not the compatible type to an int in any ways.