Learning by doing: Reading books and trying to understand the (code) examples
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
1.7 KiB

  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. char *getLine(void);
  5. char *trim(char *phrase);
  6. char *getLine(void) {
  7. const size_t sizeIncrement = 10;
  8. char *buffer = malloc(sizeIncrement);
  9. char *currentPosition = buffer;
  10. size_t maximumLength = sizeIncrement;
  11. size_t length = 0;
  12. int character;
  13. if (currentPosition == NULL) {
  14. return NULL;
  15. }
  16. while (1) {
  17. character =fgetc(stdin);
  18. if (character == '\n') {
  19. break;
  20. }
  21. if (++length >= maximumLength) {
  22. char *newBuffer = (char*) realloc(buffer, maximumLength += sizeIncrement);
  23. if (newBuffer == NULL) {
  24. free(buffer);
  25. return NULL;
  26. }
  27. currentPosition = newBuffer + (currentPosition - buffer);
  28. buffer = newBuffer;
  29. }
  30. *currentPosition++ = character;
  31. }
  32. *currentPosition = '\0';
  33. return buffer;
  34. }
  35. char *trim(char *phrase) {
  36. char *old = phrase;
  37. char *new = phrase;
  38. // skip blank chars
  39. while (*old == ' ') {
  40. old++;
  41. }
  42. while (*old) {
  43. *new = *old;
  44. new++;
  45. old++;
  46. }
  47. // set string end char
  48. *new = 0;
  49. return (char*) realloc(phrase, strlen(phrase) + 1);
  50. }
  51. int main(void) {
  52. // this is wrong -> realloc in trim() on array which wasn't malloc'ed
  53. // char blub[] = " wurstgesicht";
  54. // printf("%s\n", trim(blub));
  55. // by using return value of getline(), we got an array which was malloc'ed
  56. char *buffer = trim(getLine());
  57. if (buffer == NULL) {
  58. printf("%s\n", "out of memory");
  59. } else {
  60. printf("%s\n", buffer);
  61. free(buffer);
  62. }
  63. return 0;
  64. }