#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
char *s;
s = (char *)malloc(sizeof(char) * 128);
if(s == NULL)
{
puts("Allocation Error (malloc)");
exit(1);
}
printf("Type a string up to 127 characters: ");
fgets(s, 127, stdin);
puts("Your string is: ");
printf("%s", s);
// Preserve the exact amount of memory that the user consume,
// and free the rest. If user consume 10 chars we release 128 - (10 + 1)
if (realloc(s, sizeof(char) * (strlen(s) + 1)) == NULL)
{
puts("Allocation Error (realloc)");
exit(1);
}
puts("Your string is after free no need memory: ");
printf("%s", s);
free(s);
return 0;
}
/*
run:
Type a string up to 127 characters: have fun
Your string is:
have fun
Your string is after free no need memory:
have fun
*/