Home c How to Expand the string with realloc?

How to Expand the string with realloc?

Author

Date

Category

How can you expand the dynamic character array (row) using realloc () ?


Answer 1, Authority 100%

You can often see about this code:

char * string = malloc (...);
/ * ... * /
String = realloc (...);

This code contains a common error: if the realloc execution failed, then String will be recorded NULL and we will lose access to the pointer, which It was originally received by calling Malloc . Therefore, we will get a memory leakage.

The correct ideome solution will record the result of the execution of realloc in a temporary variable, check the successfulness of the realloc call, and only then (if the call was successful) overwrite the original variable:

char * string = malloc (...);
if (String == NULL) {
  / * ... * /
}
/ * ... * /
char * temp = realloc (string, ...);
If (Temp! = NULL) {
  String = Temp;
}

It is important to note that with the successful execution of realloc deallocies the old object, so immediately after the realloc pointer String in becomes unfuldeal and Cannot be used hereinafter.


Full example:

# include & lt; stdio.h & gt;
#Include & lt; stdlib.h & gt;
#Include & lt; String.h & gt;
INT MAIN (Void)
{
  char * s = malloc (6);
  if (s == null) {
    FPRINTF (STDERR, "CAN NOT MALLOC (). \ n");
    Return EXIT_FAILURE;
  }
  STRCPY (S, "Hello");
  Puts (s);
  char * temp = realloc (s, 14);
  if (temp == null) {
    FPRINTF (STDERR, "CAN NOT REALLOC (). \ n");
    free (s);
    Return EXIT_FAILURE;
  }
  s = temp;
  STRCPY (S, "Hello, World!");
  Puts (s);
  free (s);
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions