Search code examples
cdynamic-memory-allocationsystem-calls

calloc / malloc and read weird behavior?


I'm trying to keep a dynamically allocated array of strings that are read in using the read system call in c. Here is a small sample of what I am trying to do:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

void processInput() {
    char ** array = (char **) calloc(20, sizeof(char*));
    int arrayIndex = 0;
    while(1) {
        printf("Type something: ");
        fflush(stdout);

        char* buffer;
        int readResult = read(0, buffer, 100);

        array[arrayIndex] = (char*)calloc(readResult, sizeof(char));
    }
}    

However, this causes some strange issues:


    Type something: a
    Type something: Type something: a
    Type something: Type something: abcdefg
    Type something: Type something: Type something: Type something: Type something: Type something: Type something: Type something: 

Is there any explanation for this? I can't seem to figure out why this is happening.


Solution

  • Replace:

    char *buffer;
    

    with:

    char buffer[100];
    

    The dimension is consistent with the argument to read(), but your string will not be null terminated by read(), so you may prefer to allocate 101 bytes instead and forcibly null terminate it. You need to think about that extra byte when allocating the space.

    Note that the space that is allocated is not used.

    You should always error check memory allocations before using them.

    Since you only allocate 20 pointers before the loop, the while (1) loop is dangerous and could allow you to trample well beyond the allocated space if the user inputs more than 20 lines of data.

    (Note that if the user redirects input from a file, you won't be reading 20 lines; you'll be reading 2000 characters in 20 blocks of 100 characters, newlines and all, and then running into crash territory.)