Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
577 views
in Technique[技术] by (71.8m points)

checking that `malloc` succeeded in C

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...