Home > other >  i try to allocated with realloc function and get error
i try to allocated with realloc function and get error

Time:04-02

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...

CodePudding user response:

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.

CodePudding user response:

This line is bad:

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

This line is resizing the array to i elements. Then, in the next iteration, some value is stored to the i-th element of the array (pointed at by) strings. The array has only i elements (0 to i-1), so this is out-of-range access.

Allocate enough elements to fix:

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

Also note that casting results of malloc() family is considered as a bad practice.

  • Related