1

我在互联网上找不到任何有关的问题。我在 Linux Wheezy 发行版(Raspberry Pi,但这不相关)上运行了一小段 C 代码:

void function(const char * command)
{

    // Define commands for in between parameters
    char commandPre[] = "echo ";

    // Get the lengths of the strings
    int len= strlen(command) + strlen(commandPre);


    // Allocate the command
    char * fullCommand = (char *) malloc(len * sizeof(char));

    // Build the command
    strcat(fullCommand, commandPre);
    strcat(fullCommand, command);


    // Execute command
    system(fullCommand);

    // Free resources
    free(fullCommand);
}

现在,我正在从一个守护程序运行这段代码。但是当它第二次达到 free(fullCommand) 时(当我的程序中第二次调用函数时),程序崩溃并存在。当我删除 free(fullCommand) 时,它按预期工作。

我的问题是:system() 是否已经为我释放了“fullCommand”?如果是这样,为什么它第二次而不是第一次起作用?我在这里错过了什么吗?

PS 实际上命令是由几个字符串组成的,但上面是最基本形式的代码

4

2 回答 2

3

您有缓冲区溢出,因为您没有为字符串终止符分配空间。

Also, don't cast the return value of malloc(), and check the return value before assuming the allocation worked.

Also, as you point out in your own answer, using strcat() on a newly allocated buffer is broken since the buffer won't be an empty string. Sorry for not picking that up earlier.

于 2013-06-04T11:53:10.750 回答
-1

I found my error:

    // Allocate the command
    char * fullCommand = (char *) malloc(len * sizeof(char));

    // Build the command
    strcat(fullCommand, commandPre);

There is no guarantee that fullCommand is empty after a malloc. strcat places the second argument's first character in the place of the first arguments terminator. However, the terminator might or might not appear on the first location of the allocated array since the data in the memory after a malloc is random. Fixed it by doing:

// Allocate the command
char * fullCommand = calloc(len, sizeof(char));

Alternatively, I could have done:

// Allocate the command
char * fullCommand = malloc(len * sizeof(char));
fullCommand[0] = '\0';

Or als Alk pointed out in the comments, start with a strcpy:

// Allocate the command
char * fullCommand = malloc(len * sizeof(char));

// Build the command
strcpy(fullCommand, commandPre);
于 2013-06-04T12:33:23.167 回答