Skip to content

Instantly share code, notes, and snippets.

@cengiz-io
Created July 1, 2015 20:05
Show Gist options
  • Save cengiz-io/e654c81f4c7e92a263c6 to your computer and use it in GitHub Desktop.
Save cengiz-io/e654c81f4c7e92a263c6 to your computer and use it in GitHub Desktop.
//
// Created by Cengiz Can on 01/07/15.
//
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
void quit() {
perror("memory exhausted\n");
exit(1);
}
int main() {
size_t max = 20;
char *name = (char *) malloc(max);
if (name == 0) {
quit();
}
printf("Enter stuff:\n");
while (1) {
int c = getchar();
if (c == EOF)
break;
if (!isspace(c)) {
ungetc(c, stdin);
break;
}
}
int i = 0;
while (1) {
int c = getchar();
if (c == '\n' || c == EOF) {
name[i] = 0;
break;
}
name[i] = (char) c;
if (i == max - 1) {
max = max + max;
name = (char *) realloc(name, max);
if (name == 0) quit();
}
i++;
}
printf("Hello %s\n", name);
free(name);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment