我在C中閱讀了關於動態數組的問題,但是我無法將答案與我的問題聯繫起來。如何動態地爲C中的字符串數組分配內存?
我使用fgets從stdin
獲取命令,刪除換行符,然後希望將每個由空格分隔的命令存儲在動態分配的字符串數組中。然而,我正在分配和重新分配內存的正確方式遇到很多麻煩。我與clang
編制和不斷收到分段錯誤11.然後我用-fsanitize=address
並不斷收到:
==2286==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60200000eeb8 at pc 0x000108fb6f85 bp 0x7fff56c49560 sp 0x7fff56c49558 WRITE of size 8 at 0x60200000eeb8 thread T0
這裏是我的代碼:
// 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++;
}
}
的可能的複製[分段故障而無法理性內存分配如何,看起來好像沒什麼問題(http://stackoverflow.com/questions/35542391/segmentation-fault-but-unable-to-reason- how-memory-allocation-looks-fine-to-me) –
不要將'malloc'和朋友的結果放在C中,並且C沒有字符串類型。這只是一種慣例。 – Olaf