0

I have a struct with a 2d char array that can be modified, I should be able to increase the number of rows in the 2d array, I managed to do that but I run into a problem where after the fourth row I can't allocate more space, I tried to change the length of the array to be smaller and in that case, the same problem accord after four times, and the return value of the realloc() isn't NULL and I can't exit the program.

This is the struct:

struct Buffer{
    /*--buffer--*/
    
    /*2d array that store the whole text */
    char **text;
    /* number of rows */
    int count;
};

the program reads text and after 60 characters it should create a new row

    /*initialize a buffer */
    struct Buffer* buffer = (struct Buffer*)malloc(sizeof(struct Buffer));
    buffer->text = (char**)malloc(sizeof(char*));
    buffer->text[0] = (char*)malloc(sizeof(char)*61);
    buffer->count = 1;
    /*start reading the text*/
    readText(1, buffer);
    printf("\nFixed output: \n");
    /*print the text*/
    printText(1, buffer);

inside readText()

    /* try to add more memory for the ADT */
    buffer->text[buffer->count-1][60] = '\0';
    if(!expandADT(1, buffer)) exit_error(0);
    buffer->text[buffer->count-1][0] = c;

int expandADT(int option, void *ptr)

    /* cast the pointer */
    struct Buffer* buffer = (struct Buffer*) ptr;
    struct Buffer* temp;
    /* increase the number of rows */
    buffer->count++;
    /* try to make space for another row */
    temp = (struct Buffer*)realloc(buffer, sizeof(*buffer->text) * buffer->count);
    /* if the buffer is NULL it means that we don't have enough space and we return an error*/
    if(temp == NULL) return 0;
    buffer = temp;
    buffer->text[buffer->count-1] = (char*)malloc(sizeof(char)*61);
    if(buffer->text[buffer->count-1] == 0) return 0;

If the array runs out of space it should print a message and close the program, however the term

if(temp == NULL) return 0;

in expandADT() isn't correct and the program keeps running. then it stops at the code line -

buffer->text[buffer->count-1][0] = c; /* c is an input character */

at readText() after the program tried to expand the array.

For input that is larger than 60*4. There is no output whatsoever from the program and it closes.

0 Answers0