EXC_BAD_ACCESS error by reallocate memory

101 views Asked by At

I am trying to make dynamic double array, but I have a problem with BAD_ACCSESS.

int execute(person* person_array)
{
char** parsed_command;
if(!(parsed_command = malloc(sizeof(char*)))){
    error_notification(12);
    return 2;
}
parsed_command[0] = malloc(SIZE_ARG*sizeof(char));
char command[MAX_BUFFER_SIZE];
string quit = "quit\n";
do{
    printf("esp> ");
    if(fgets(command, MAX_BUFFER_SIZE, stdin)==NULL){  // save input in "command"
        return 2;
    }
    parse_command_input(command, person_array, &parsed_command);
}while(strcmp(command,quit));
printf("Bye.\n");
free(&parsed_command[0]);
free(parsed_command);
return 0;
}

void parse_command_input(const char* command, person* person_array, char*** parsed_command){
char* delim = strtok(command, " ");
int counter = 0;
while (delim != NULL){
    if(counter > 0) {
        char **tmp = realloc(*parsed_command, (counter+1)*sizeof(char*));
        if(tmp!=NULL)
            *parsed_command = tmp;
        else{
            error_notification(12);
        }
        *parsed_command[counter] = malloc(SIZE_ARG*sizeof(char)); //ERROR
    }
    strcpy(*parsed_command[counter], delim);
    counter++;
    delim = strtok (NULL, " \n");
}
which_command(parsed_command, counter, person_array);
}    

So, I initialise parsed_command in execute(), and then reallocate it in parsed_command_input() when i have more then one word in input. By reallocating parsed_command at the first time everything is ok, but on the second reallocating round the address of parsed_command changes, and i have BAD_ACCSESS by malloc (add memory for line).

How can I fix it?

Thanks in advance

1

There are 1 answers

2
user253751 On BEST ANSWER

*parsed_command[counter] means the same as *(parsed_command[counter]) but you meant it to be (*parsed_command)[counter] so write that.