Search code examples
cmallocvalgrindrealloc

Reallocing an array of strings


So I made this function that receives an unknown amount of strings and adds them into an array of strings.

char **receiveCode(int socket){
    int line = 0;
    size_t lines = 1;
    size_t size = 1;
    char** code = malloc(sizeof(char)*size);

    while(1){
        package_struct *aPackage = receivePackage(socket);
        if(aPackage->type=='F'){break;}
        size = size + aPackage->size;
        code = realloc(code, size);
        code[line] = malloc(sizeof(char)*aPackage->size);
        strcpy(code[line],aPackage->package);
        line++;
        lines++;
        free(aPackage);
    }
    code = realloc(code, size + 2);
    code[line] = malloc(sizeof(char)*3);
    code[lines]=NULL;
    return code;
}

Sometimes when I run this code I get the following error

* glibc detected ./pp: realloc(): invalid next size: 0x00007f0f88001220 **

Which, according to Valgrind, happens in that function.

Probably I am using too many mallocs and reallocs... not sure though.


Solution

  • I think the problem is this :

    char** code = malloc(sizeof(char)*size);
    

    It should be char * instead of char inside sizeof()

    char** code = malloc(sizeof(char*)*size);
    

    Since code is a pointer to string so allocate memory for pointers that is char*

    Also there is same kind of problem in realloc