Search code examples
cstructwhile-loopdynamic-memory-allocationrealloc

i try to allocated with realloc function and get error


typedef struct{
   char** strings_cmd;
   int size_cmd;
}parseInfo;

....

parseInfo* parse(char* cmd){
    char* temp = strdup(cmd);
    char* temp_split = strtok(temp," ");
    int i = 0;
    char** strings = (char**)malloc(sizeof(char*));
    if(strings == NULL){
        printf("no memory allocated strings parse()\n");
        exit(1);
    }
    while(temp_split != NULL){
        strings[i++] = strdup(temp_split);
        strings = realloc(strings,i * sizeof(char*));
        if(strings == NULL){
            printf("no memory allocated strings (while) parse()\n");
            exit(1);
        }   
        temp_split = strtok(NULL," ");
    }
    strings[i] = NULL;
    parseInfo* info = (parseInfo*)malloc(sizeof(parseInfo));
    if(info == NULL){
        printf("no memory allocated info parse()\n");
        exit(1);
    }
    info->strings_cmd = strings;
    info->size_cmd = i;
    return info;
}

hello guys i get the error:

realloc(): invalid next size.

and what i try to do is to input a string and split it down into words for example i input = "Hello World". and to split it = "Hello" , "World"

but when i pass 4 words i got this error...


Solution

  • For starters the function has a memory leak because in the beginning of the function there is allocated memory

    parseInfo* parse(char* cmd){
        char* temp = strdup(cmd);
        //...
    

    that was not freed.

    In this while loop

    while(temp_split != NULL){
        strings[i++] = strdup(temp_split);
        strings = realloc(strings,i * sizeof(char*));
        if(strings == NULL){
            printf("no memory allocated strings (while) parse()\n");
            exit(1);
        }   
        temp_split = strtok(NULL," ");
    

    You need to wirte

    strings = realloc(strings, ( i + 1 ) * sizeof(char*));
    

    to reserve one element for the terminating null pointer used in this statement

    strings[i] = NULL;
    

    And you will need to free the allocated dynamically memory in the beginning of the function like

    free( temp );
    
    }
    

    you are allocating an array of pointers with one less element that it is required.