Search code examples
carrayspointersmemory-managementrealloc

Error at execution because of realloc


i wrote a little console program which stores words in an array, represented by
char** test_tab, and then print them.

The program works fine as long as it does not go through the conditionalrealloc()
(e.g if i increase sizeto 1000).
But if realloc() get called the program crashes during the array printing, probably because the memory is messed up in there.

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

char* get_word();

int main(int argc, char* argv[])
{
    size_t size = 100;
    size_t nb_pointer = 0;
    char** test_tab = malloc(size * sizeof *test_tab);
    char** temp_tab;

    while((*(test_tab + nb_pointer) = get_word()) != NULL)
    {
        nb_pointer++;
        if(nb_pointer >= size)
        {
            size += 100;
            temp_tab = realloc(test_tab, size);

            if(temp_tab != NULL)
                test_tab = temp_tab;
            else
            {
                free(test_tab);
                exit(1);
            }
        }
    }

    for(nb_pointer = 0; *(test_tab + nb_pointer) != NULL; nb_pointer++)
        printf("%s\n", *(test_tab + nb_pointer));

    free(test_tab);

    return 0;
}

Can someone explains me what i am doing wrong right here? Thanks.


Solution

  • The amount of memory in the realloc is not calculated correctly.

           temp_tab = realloc(test_tab, size);
    

    should be

           temp_tab = realloc(test_tab, size * sizeof *test_tab);