Reputation: 3
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.
#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);
}
Upvotes: 0
Views: 43
Reputation: 75062
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.
Upvotes: 1