我阅读了有关C语言中动态数组的先前问题,但是无法将答案与我的问题联系起来。
我从stdin
使用fgets中获取命令,删除了换行符,然后希望将每个命令以空格分隔存储在动态分配的字符串数组中。但是,我在分配和重新分配内存的正确方法上遇到了很多麻烦。我正在编译clang
并不断出现细分错误11。然后-fsanitize=address
,我使用并不断得到:
== 2286 ==错误:AddressSanitizer:pc 0x000108fb6f85 bp上地址0x60200000eeb8上的堆缓冲区溢出0x7fff56c49560 sp 0x7fff56c49558在0x60200000eeb8线程T0上写入大小8
这是我的代码:
// Sets a delimiter to split the input
const char *seperator = " ";
char *token = strtok(line, seperator);
char **cmds = (char **) malloc(sizeof(char) * sizeof(*cmds));
// Adds first token to array of delimited commands
cmds[0] = token;
int count = 1;
while (token != NULL) {
token = strtok(NULL, sep);
if (token != NULL) {
cmds = (char **) realloc(cmds, sizeof(char) * (count + 1));
// Adds next token array of delimited commands
cmds[count] = token;
count++;
}
}
您没有分配足够的内存。cmds
是一个指针数组,因此每个元素都是sizeof(char *)
字节,而不是sizeof(char)
字节。
在初始分配中,您需要1 char *
,然后在后续分配中,您需要count + 1
。
另外,请勿转换的返回值malloc
,因为这可能会隐藏其他问题,并且不要忘记检查失败。
char **cmds = malloc(sizeof(char *) * 1);
if (cmds == NULL) {
perror("malloc failed");
exit(1);
}
...
cmds = realloc(cmds, sizeof(char *) * (count + 1));
if (cmds == NULL) {
perror("reallocfailed");
exit(1);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句