【发布时间】:2016-04-14 04:53:44
【问题描述】:
我阅读了之前关于 C 中动态数组的问题,但是我无法将答案与我的问题联系起来。
我正在使用 fgets 从stdin 获取命令,删除换行符,然后希望将每个由空格分隔的命令存储在动态分配的字符串数组中。但是,我在分配和重新分配内存的正确方法上遇到了很多麻烦。我正在使用clang 编译并不断收到分段错误11。然后我使用-fsanitize=address 并不断收到:
==2286==错误:AddressSanitizer:地址上的堆缓冲区溢出 0x60200000eeb8 在 pc 0x000108fb6f85 bp 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++;
}
}
【问题讨论】:
-
不要把
malloc&friends的结果用C转换。而且C没有字符串类型。这都是惯例。
标签: c malloc dynamic-memory-allocation realloc strtok