fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. #define INCREMENT_SIZE 10
  5.  
  6. int main(void) {
  7. char* buffer = (char*)malloc(sizeof(INCREMENT_SIZE + 1));
  8. char* current = buffer;
  9. char ch;
  10. int length = 0;
  11. int maxLength = strlen(buffer);
  12.  
  13. while (1)
  14. {
  15. ch = getchar();
  16. if (ch == '\n')
  17. break;
  18.  
  19. if (++length >= maxLength)
  20. {
  21. char* newBuffer = realloc(buffer, maxLength + INCREMENT_SIZE);
  22.  
  23. if (newBuffer == NULL)
  24. {
  25. free(buffer);
  26. return 0;
  27. }
  28.  
  29. maxLength += INCREMENT_SIZE;
  30. current = newBuffer + (current - buffer);
  31. buffer = newBuffer;
  32. }
  33.  
  34. *current++ = ch;
  35. }
  36.  
  37. *current = '\0';
  38. printf("%s\n", buffer);
  39. printf("%d\n", strlen(buffer));
  40.  
  41. return 0;
  42. }
  43.  
Success #stdin #stdout 0s 2428KB
stdin
123456789012345678901234567890456789
stdout
123456789012345678901234567890456789
36