繁体   English   中英

如何在C中为字符串数组动态分配内存?

[英]How do I dynamically allocate memory for an array of strings in C?

我阅读了有关C语言中动态数组的先前问题,但是无法将答案与我的问题联系起来。

我正在使用fgets从stdin获取命令,删除了换行符,然后希望将每个由空格分隔的命令存储在动态分配的字符串数组中。 但是我在分配和重新分配内存的正确方法上遇到了很多麻烦。 我正在使用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);
        }

首先,根据定义, sizeof(char)始终为1。 而且编码不会使您的代码更具可读性。

但是指向char的指针需要sizeof(char*)个字节(取决于机器和ABI ,通常为8或4个字节)。 如果使用GCC,我至少建议使用gcc -Wall -Wextra -g编译您的代码。

最后,我发现您的代码效率低下。 您正在每个循环调用realloc 我将维护一个包含分配大小的变量

 int allocsize = 4; // allocated size in number of elements
 char **cmds = malloc(allocsize*sizeof(char*));
 if (!cmds) { perror("malloc"); exit(EXIT_FAILURE); };

(顺便说一句,请始终检查 malloc的结果;它可能会失败)。

并避免realloc -ing每一次,我会以几何方式增长分配的大小,所以在循环中:

 if (count>=allocsize) {
    int newallocsize = (4*allocsize)/3+10;
    cmds = realloc (cmds, newallocsize*sizeof(char*));
    if (!cmds) { perror("realloc"); exit(EXIT_FAILURE); };
    allocsize = newallocsize;
 }

另外,也可以不使用三个变量: cmdscountallocsize ,而可以使用以灵活数组成员结尾的单个struct (并保持其分配和使用的大小)。

  • 第一个malloc是错误的。如果在分配之前用* cmd代替cmd,会得到什么?
  • 它还使用sizeof(char),这是错误的。

正确的方法是..

// strtok modifies the string. So use writable string
char line[80] = "Hello my name is anand";
char *token = strtok(line, sep);
int count = 0;
// Alloc array of char* for total number of tokens we have right now
char **cmds = (char **) malloc(sizeof(char*) * (count + 1));

while (token != NULL) 
{
    /**
     * Alloc memory for the actual token to be stored.. 
     * token returned by strtok is just reference to the existing string 
     * in 'line'
     */
    cmds[count] = malloc(sizeof(char) * ((strlen(token) + 1)));
    // Adds tokens to array of delimited commands
    strcpy(cmds[count], token);
    count++;

    token = strtok(NULL, sep);
    if (token != NULL) 
    {
        // resize array of tokens to store an extra token
        char ** newCmds = (char **) realloc(cmds, sizeof(char*) * (count + 1));
        // only if realloc was successful then use it.
        if (newCmds != NULL)
        {
             cmds = newCmds;
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM