#include #include #include #include #include #define NAME_LENGTH (2) #define INITIAL_LINE_LENGTH (2) void myfree(void * p); void * mymalloc(size_t s); void * myrealloc(void *ptr, size_t size); bool debugflag; void * mymalloc(size_t s){ void * ptr = malloc(s); memset(ptr, 0, s); if (debugflag) { printf("Mymalloc: %zu bytes: %p\n", s, ptr); } return ptr; } void * myrealloc(void *ptr, size_t s){ void * p = realloc(ptr, s); if (debugflag) { printf("Myrealloc: %zu bytes: %p oldp: %p\n", s, p, ptr); } return p; } void myfree(void * p){ if (debugflag) { printf("Myfree: %p \n", p); } free(p); } /* return a freshly-malloc'd line with next line of input from stdin */ char * getLine(void) { char *line; int size; /* how much space do I have in line? */ int length; /* how many characters have I used */ int c; size = INITIAL_LINE_LENGTH; line = mymalloc(size); assert(line); length = 0; while((c = getchar()) != EOF && c != '\n') { if(length >= size-1) { /* need more space! */ size *= 2; /* make length equal to new size */ /* copy contents if necessary */ line = myrealloc(line, size); } line[length++] = c; } line[length] = '\0'; return line; } int main(int argc, char **argv) { int x = 12; /* char name[NAME_LENGTH]; */ char *line; int y = 17; puts("What is your name?"); debugflag = true; /* gets(name); */ /* may overrun buffer */ /* scanf("%s\n", name); */ /* may overrun buffer */ /* fgets(name, NAME_LENGTH, stdin); */ /* may truncate input */ line = getLine(); /* has none of these problems */ printf("Hi %s! Did you know that x == %d and y == %d?\n", line, x, y); myfree(line); /* but we do have to free line when we are done with it */ return 0; }