Answer to Question #276897 in C for Cook

Question #276897

Write a program for the memory management.

1
Expert's answer
2021-12-08T08:32:00-0500
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main() {


   char text[200];
   char *descr;


   strcpy(text, "Abraham Lincoln");


   /*Dynamically allocating the memory */
   descr = malloc( 30 * sizeof(char) );
	
   if( descr == NULL ) {
      fprintf(stderr, "Error - Cannot allocate the required memory\n");
   } else {
      strcpy( descr, "Abraham Lincoln was the best in software development\n.");
   }
	
   /* When you want to store bigger text in the memory*/
   descr = realloc( descr, 200 * sizeof(char) ); //Reallocating the memory
	
   if( descr == NULL ) {
      fprintf(stderr, " Error - Cannot allocate the required memory\n");
   } else {
      strcat( descr, "He graduated from the top university in the world\n");
   }
   
   printf("Name = %s\n", text );
   printf("Description: %s\n", descr );


   /* Releasing the memory by using the function free()  */
   free(descr);
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS