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
286 views
in Technique[技术] by (71.8m points)

c - Is it safe to use realloc?

Some time ago a friend of mine told me not to use realloc because it's unsafe, but he couldn't tell me why, so I made some research on the subject and the nearest references to my doubt were:

  1. First
  2. Second

I want to know if I can continue to use realloc in my code or if it's unsafe is there any other way to reallocate memory?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

It's perfectly safe to use realloc. It is the way to reallocate memory in a C program.

However you should always check the return value for an error condition. Don't fall into this common trap:

p = realloc(p, new_size); // don't do this!

If this fails, realloc returns NULL and you have lost access to p. Instead do this:

new_p = realloc(p, new_size);
if (new_p == NULL)
    ...handle error
p = new_p;

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

...