You need to modify the check to check against the returned pointer, not the content. Something like
if( p == NULL) {
fprintf(stderr, "The pointer points nothing !\n");
return 1;
}
should do. Quoting the standard regarding the return values:
The malloc
function returns either a null pointer or a pointer to the allocated space.
The null pointer is returned in case of a failure, otherwise the pointer returned should be non-equal to a null pointer.
That said,
The initial content of the pointed memory is indeterminate, do not attempt to verify it. Quoting from the standard,
The malloc
function allocates space for an object whose size is specified by size
and
whose value is indeterminate.
That goes for your other question regarding "checking the length" of the pointer - it's pointless. Unless you have stored (write) some value into it - there's no point trying to measure the initial content, as it is indeterminate. You may eventually run into undefined behavior.
The cast for the returned pointer by malloc()
and family is superfluous. It can be totally avoided in C.
sizeof(char)
is guaranteed to be 1, in C. Thus, using sizeof(char)
as a multiplier, is again not needed, per se.