[英]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.我正在尝试通过另一个函数进行
malloc
和分配指令和分隔符。 With everything I have tried, I get a segmentation fault on the second assignment *separators[1] = '1'
, but for some reason, *separators = '2'
works.通过我尝试过的一切,我在第二个分配
*separators[1] = '1'
上遇到了分段错误,但由于某种原因, *separators = '2'
有效。
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);
}
Expressions like表达式如
*separators[1] = (char)'1';
won't work well due to the operator precedence .由于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. []
运算符的优先级高于*
运算符,因此它会尝试写入separators
的第二个元素,而它所指向的“数组”只有一个元素。
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. + 1
只会增加一个字节的分配大小,而不是一个元素的大小。 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 .请注意,
malloc()
系列的转换结果被认为是一种不好的做法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.