Write a program for the memory management.
#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);
}
Comments
Leave a comment