简体   繁体   中英

Malloc and Assignment inside another function

I need help to understand why this is not working.

I'm trying to malloc and assign instructions and separators through another function. With everything I have tried, I get a segmentation fault on the second assignment *separators[1] = '1' , but for some reason, *separators = '2' works.

I think there is something I don't understand with referenced pointers.


Here is my simplified code

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>

void        split_instructions(char ***instructions, char **separators)
{
    int split_len = 2;

    *instructions = (char **)malloc(sizeof(char*) * split_len + 1);
    if (*instructions == NULL)
        return;
    *separators = (char *)malloc(sizeof(char) * split_len + 1);
    if (*separators == NULL)
    {
        free(instructions);
        return;
    }
    *separators[0] = (char)'q';
    *separators[1] = (char)'1';
    //*separators = "22"; <- this work
    *instructions[0] = (char*)"test";
    *instructions[1] = (char*)"test2";
}

int main(void)
{
   char **instructions;
   char *separators;
   
   split_instructions(&instructions, &separators);
}

Expressions like

*separators[1] = (char)'1';

won't work well due to the operator precedence .

The [] operator has higher precedence than * operator, so it will try to write to the 2nd element of separators while there is only one element for the "array" pointed at by that.

It should be written like

(*separators)[1] = (char)'1';

Also note that the allocation size in

*instructions = (char **)malloc(sizeof(char*) * split_len + 1);

looks weird. The + 1 will increase the allocation size by only one byte, not size of one element. If you should allocate for another element, it should be

*instructions = malloc(sizeof(char*) * (split_len + 1));

or

*instructions = malloc(sizeof(**instructions) * (split_len + 1));

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM