If there's not enough memory, then you shouldn't be dereferencing ptr or printing the non-existent string. I would also do a bit of error checking on the value entered, e.g., make sure that it is positive (and perhaps set an upper bound). For actually reading the string, you might as well use fgets instead of writing a loop with getc. Combining these ideas, I might rewrite your program to something like this:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
int num;
int c;
char *ptr;
printf("Insert the number of characters: ");
if (scanf("%d", &num) != 1)
{
fprintf(stderr, "There was an input error, please try again.\n");
return EXIT_FAILURE;
}
if (num <= 0)
{
fprintf(stderr, "The number of characters must be positive, please try again.\n");
return EXIT_FAILURE;
}
/* discard characters remaining on the standard input stream */
while ((c = fgetc(stdin)) != '\n' && c != EOF);
++num; /* account for the null character */
ptr = malloc(num * sizeof(*ptr));
if (!ptr)
{
fprintf(stderr, "There is not enough memory.\n");
return EXIT_FAILURE;
}
printf("Insert the text: ");
if (!fgets(ptr, num, stdin))
{
fprintf(stderr, "There was an input error, please try again.\n");
free(ptr);
return EXIT_FAILURE;
}
ptr[strcspn(ptr, "\n")] = '\0'; /* get rid of newline character, if it exists */
printf("Characters inserted are: %s\n", ptr);
free(ptr);
return 0;
}