achulkov2

Untitled

Dec 13th, 2018
449
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. enum { DEFAULT = 4 };
  5.  
  6. int add(char** ptr, size_t *a, size_t *u, int c) {
  7. if (*u == *a) {
  8. if (*a == 0) {
  9. *a = DEFAULT;
  10. }
  11. if (__builtin_add_overflow(*a, *a, a)) {
  12. if (*ptr) {
  13. free(*ptr);
  14. }
  15. return 0;
  16. } else {
  17. char *res = realloc(*ptr, (*a) * sizeof(**ptr));
  18. if (!res) {
  19. if (*ptr) {
  20. free(*ptr);
  21. }
  22. return 0;
  23. }
  24. *ptr = res;
  25. }
  26. }
  27. (*ptr)[*u] = c;
  28. ++(*u);
  29. return 1;
  30. }
  31.  
  32. char *getline2(FILE *f) {
  33. size_t a = 0, u = 0;
  34. char *ptr = NULL;
  35. int c = fgetc(f);
  36. for (; c != '\n' && c != EOF; c = fgetc(f)) {
  37. if (!add(&ptr, &a, &u, c)) {
  38. return NULL;
  39. }
  40. }
  41. if (c == '\n') {
  42. if (!add(&ptr, &a, &u, c)) {
  43. return NULL;
  44. }
  45. }
  46. if (ptr) {
  47. if (!add(&ptr, &a, &u, '\0')) {
  48. return NULL;
  49. }
  50. }
  51. return ptr;
  52. }
Add Comment
Please, Sign In to add comment