fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main(void)
  5. {
  6. int inputAsingleChar, i=0, j=4;
  7.  
  8. /* initial allocation */
  9. char *name = malloc(j);
  10. if (name == NULL) {
  11. /* Handle malloc failure */
  12. }
  13.  
  14. printf("Your name: \n");
  15. while((inputAsingleChar = getchar()) != '\n' && inputAsingleChar != EOF)
  16. {
  17. /* reallocate as needed */
  18. if (i == j) {
  19. j *= 2;
  20. char *tmp = realloc(name, j);
  21. if(tmp == NULL){
  22. /* Handle realloc failure */
  23. } else {
  24. /* no need to realloc() again, and no need to free tmp */
  25. name = tmp;
  26. }
  27. }
  28. /* store current character */
  29. name[i++] = inputAsingleChar ;
  30. }
  31.  
  32. /* add null terminator */
  33. name[i] = '\0';
  34.  
  35. printf("Name: %s \n", name);
  36. free(name);
  37.  
  38. return 0;
  39. }
  40.  
Success #stdin #stdout 0s 10320KB
stdin
This is a test which is long enough to require a few reallocations.
stdout
Your name: 
Name: This is a test which is long enough to require a few reallocations.