Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- enum { DEFAULT = 4 };
- int add(char** ptr, size_t *a, size_t *u, int c) {
- if (*u == *a) {
- if (*a == 0) {
- *a = DEFAULT;
- }
- if (__builtin_add_overflow(*a, *a, a)) {
- if (*ptr) {
- free(*ptr);
- }
- return 0;
- } else {
- char *res = realloc(*ptr, (*a) * sizeof(**ptr));
- if (!res) {
- if (*ptr) {
- free(*ptr);
- }
- return 0;
- }
- *ptr = res;
- }
- }
- (*ptr)[*u] = c;
- ++(*u);
- return 1;
- }
- char *getline2(FILE *f) {
- size_t a = 0, u = 0;
- char *ptr = NULL;
- int c = fgetc(f);
- for (; c != '\n' && c != EOF; c = fgetc(f)) {
- if (!add(&ptr, &a, &u, c)) {
- return NULL;
- }
- }
- if (c == '\n') {
- if (!add(&ptr, &a, &u, c)) {
- return NULL;
- }
- }
- if (ptr) {
- if (!add(&ptr, &a, &u, '\0')) {
- return NULL;
- }
- }
- return ptr;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement