Lena Bru
Lena Bru

Reputation: 13947

Why do i get bad access

I have a struct as follows

struct cmd{

  char **tokenized_cmd;
  int num_params;
}

in some function with the signature i have the following

void parse_cmd(cmd, char *line){

    char *token;
    char *saveptr;
    char *delim_space;
    char *delim_comma;
    char *delim_new_line;
    char **result;
    int i;
    int j=0;
    command.num_params = 0;
    delim_space = " ";
    delim_comma = ",";
    delim_new_line = "\n";
    if(line!=NULL){
        line = strtok(line,delim_new_line);
        token = strtok_r(line,delim_space,&saveptr);
    }
    result[j]=token;
    j++;
    for (i=0;i<3;i++){
        token = strtok_r(NULL, delim_comma, &saveptr);
        if(token!=NULL){
            result[j] = token;
            j++;
        }else{
            result[j]='\0';
            break;
        }
    }
    command.tokenized_cmd = result;
    command.num_params = j;

    if(command.tokenized_cmd[0] == '\0'){
     printf("empty");
    }

}

why does this piece of code :

if(command.tokenized_cmd[0] == '\0'){
     printf("empty");
    }

cause bad access error ?

this doesnt seem to fix the problem:

 command.tokenized_cmd = malloc(sizeof(result));
    for(i=0;i<j;i++){
        command.tokenized_cmd[i]= malloc(sizeof(result[i]));
        command.tokenized_cmd[i] = result[i];
    }
    command.num_params = j;

Upvotes: 0

Views: 301

Answers (1)

Alex Reynolds
Alex Reynolds

Reputation: 96986

You do not appear to allocate space for result, and so this step should fail to provide anything accessible:

command.tokenized_cmd = result;

If result is storing multiple strings, then you need to allocate space for storing however many char * (strings) with malloc().

In addition, for each individual string or char *, you need to allocate space for that with malloc().

When you're done with result or tokenized_cmd and no longer need it, you may need to use free() to recover the memory you've allocated, to prevent a memory leak. For a double pointer (char **) that you are done with, you must free both the strings and the pointers to those strings.

Upvotes: 1

Related Questions