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
?
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 anull pointer constant
.
So, NULL
is of pointer type which is not the compatible type to an int
in any ways.
It's valid on all major platforms, except for one thing: Don't pass NULL
as the value to set. Remember that the memset
function operates on the individual bytes of the memory, and you should set all the bytes to zero ( 0
).
It is however not strictly technically valid. On most major platforms a null pointer is equal to zero. But it doesn't have to be that. The only fully portable and safe way to do it is through a manual loop where you set each pointer explicitly to NULL
.
And if anyone is interested to know, even if NULL
is defined as 0
(or ((void *) 0)
) it doesn't matter. The compiler will translate that zero into the platform-specific version of a null pointer, which may be something else than the actual integer zero.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.