Search code examples
cmallocdynamic-arrays

C - Dynamically allocating array for stdin without realloc


I have a project in which I'm working on, that's gonna take an input that comes out from another program ran on the terminal, like so:

./other_program | ./project

so I'm taking the output from other_program and using it on project with

read(0, buffer, BUFF_SIZE);

But if imagine that's not the best way to do that. I know I can iterate through stdin and just use realloc to increase the buffer size, but I'm forbidden from using realloc, due to project specifications, which say I can only use malloc, read, write, open and free.

Is there any other way out? thanks!


Solution

  • Repeatedly read data into a local buffer and append it to a big buffer.

    After reading, memory allocated to bigbuf will be right-sized to the data read.

    A more robust solution would use an exponentially (maybe 1.5x to 3x) growing bigbufsize.

    #define BUFF_SIZE 1024
    char buffer[BUFF_SIZE];
    char *bigbuf = NULL;
    size_t bigbufsize = 0;
    
    ssize_t len;
    while( (len = read(0, buffer, sizeof buffer)) > 0) {
      size_t newbigbufsize = bigbufsize + len;
      char *newbigbuf = malloc(newbigbufsize);
      if (newbigbuf == NULL) exit(1);  //Handle OOM
    
      memcpy(newbigbuf, bigbuf, bigbufsize);
      memcpy(&newbigbuf[bigbufsize], buffer, len);
      free(bigbuf);
      bigbuf = newbigbuf;
      bigbufsize = newbigbufsize;
    }
    
    // Use data
    foo(bigbuf, bigbufsize);
    
    // clean-up
    free(bigbuf);
    bigbuf = NULL;
    bigbufsize = 0;