'standard input in C with enough memory
I am developing a program that receives a command (which refers to a function) and its respective arguments from STDIN. For example: add 2 3. I thought of entering "add 2 3" as an array of characters, but I wanted to know if there is any way to allocate just enough memory for each input, so as not to waste memory, or that memory is insufficient.
Solution 1:[1]
If you're using POSIX, you can use getline to read line(s) of input and allocate memory:
char *line = NULL;
size_t len = 0;
while (getline(&line, &len, stdin) > 0) {
// read a line of input into line
... do something with it
}
free(line);
This will allocate memory as needed to hold the line read (reusing the same memory for each subsequent line, so if you want to save a line you'll need to copy it). It might allocate more than is needed for a line, but you can see how much it actually allocated in len
Solution 2:[2]
The typical way this is done is by using a growing buffer that doubles when full. This way you will use at most 2x the amount of memory you need. Even in the DOS days we didn't allocate exactly enough. That would have been disastrous.
char *getline()
{
static char *buf;
static size_t bufsiz;
if (!bufsiz) { buf = malloc(16); if (!buf) return buf; /* ERROR */ bufsiz = 16; }
size_t n = 0;
int c;
while ((c = getc(stdin)) != EOF && c != '\n') {
buf[n++] = c;
if (n == bufsiz) {
char *newbuf = realloc(buf, bufsiz << 1);
if (!newbuf) return NULL;
buf = nebuf;
bufsiz <<= 1;
}
}
buf[n] = 0;
return buf;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
