I'm guessing that you want to either store one line, or every line, that you read in. And you want the lines to be of any length. And you don't know those length(s) beforehand.
First, some background information. malloc() allocates a block of memory, the size of which can be specified at run-time, as opposed to (C89) array sizes, which must be specified at compile-time. It's very simple to use. You pass it the number of bytes to allocate, and it returns a pointer to the newly allocated memory (or NULL if there isn't enough free memory to satisfy your request):
Code:
char *p = malloc(10);
realloc() takes a block of memory that was previously allocated with malloc() -- or NULL, in which case it acts just like malloc() -- and resizes how much memory is allocated for that block of memory. That is, you can allocated more or less memory for a block of memory that has already been allocated.
Code:
char *p = malloc(10);
/* p points to 10 chars */
p = realloc(p, 20); /* bad idea to use p twice, but never mind */
/* p now points to 20 chars */
Finally, one should always free() any blocks of memory allocated with malloc():
Code:
char *p = malloc(10);
/* p points to 10 chars */
p = realloc(p, 20); /* bad idea to use p twice, but never mind */
/* p now points to 20 chars */
free(p); /* free the 20 characters */
----
So, anyway, here's some code which will read data (one line) from an input stream such as a file or stdin, resizing the buffer whenever it gets full:
Code:
#include <stdio.h>
#include <stdlib.h> /* for malloc(), realloc(), and free() */
char *get_string(FILE *fp) {
size_t size = 1, pos = 0;
char *p = malloc(size);
int c;
do {
c = getc(fp);
if(c == '\n' || c == EOF) c = 0; /* add a NULL terminator */
if(pos <= size) {
size *= 2; /* double the allocated memory */
p = realloc(p, size);
}
p[pos ++] = c;
} while(c);
printf("get_string(): %lu read, %lu allocated\n", (unsigned long)(pos-1), (unsigned long)size);
return p;
}
int main() {
char *str = get_string(stdin);
printf("string: [%s]\n", str);
free(str);
return 0;
}
It's kind of like fgets(), except that it strips the newline.