I want to allocate memory using malloc
and check that it succeeded. something like:
if (!(new_list=(vlist)malloc(sizeof (var_list))))
return -1;
how do I check success?
I want to allocate memory using malloc
and check that it succeeded. something like:
if (!(new_list=(vlist)malloc(sizeof (var_list))))
return -1;
how do I check success?
malloc
returns a null pointer on failure. So, if what you received isn't null, then it points to a valid block of memory.
Since NULL
evaluates to false in an if
statement, you can check it in a very straightforward manner:
value = malloc(...);
if(value)
{
// value isn't null
}
else
{
// value is null
}
(void*)0
is a null pointer constant. That's because a void*
pointer in C (unlike C++) can be implicitly converted to any other pointer type, so it's possible to allow NULL to have void*
type. So in both languages NULL is an implementation-defined null pointer constant, but C implementations have more freedom. –
Flavius NULL
is a null pointer constant, and that is guaranteed to evaluate to zero. If your particular implementation doesn't comply with the standard, I feel sorry for you, but on sane platforms you don't need that kind of check. –
Heartland Man page :
If successful,
calloc()
,malloc()
,realloc()
,reallocf()
, andvalloc()
functions return a pointer to allocated memory. If there is an error, they return aNULL
pointer and seterrno
toENOMEM
.
new_list=(vlist)malloc(sizeof (var_list)
if (new_list != NULL) {
/* succeeded */
} else {
/* failed */
}
The code you have already tests for error, although I normally write the assignment and check as two separate lines:
new_list = malloc(sizeof *new_list);
if (!new_list)
/* error handling here */;
(Note two small changes - you shouldn't cast the return value, and we take the size from the variable rather than its type to reduce the chance of a mismatch).
If malloc()
fails, it returns a null pointer, which is the only pointer value that is false.
The error handling you have is simply return -1;
- how you handle that in the calling function is up to you, really.
© 2022 - 2024 — McMap. All rights reserved.
vlist
is a typedef forvar_list*
. – Flavius