这个appender,realloc功能安全吗?

Mic*_*ICE 1 c

刚从一些man文档中完成了这个函数的组合,它需要一个char*并附加一个const char*,如果char*的大小太小,它会将它重新分配给更大的东西并最终附加它.自从我使用c以来已经很长时间了,所以只需要办理登机手续.

// append with realloc
int append(char *orig_str, const char *append_str) {
    int result = 0; // fail by default

    // is there enough space to append our data?
    int req_space = strlen(orig_str) + strlen(append_str);
    if (req_space > strlen(orig_str)) {
        // just reallocate enough + 4096
        int new_size = req_space;
        char *new_str = realloc(orig_str, req_space * sizeof(char));

        // resize success.. 
        if(new_str != NULL) {
            orig_str = new_str;
            result = 1; // success
        } else {
            // the resize failed.. 
            fprintf(stderr, "Couldn't reallocate memory\n");
        }
    } else {
        result = 1;
    }

    // finally, append the data
    if (result) {
        strncat(orig_str, append_str, strlen(append_str));
    }

    // return 0 if Ok
    return result;
}
Run Code Online (Sandbox Code Playgroud)

M.M*_*M.M 5

这是不可用的,因为你永远不会告诉调用者你从哪里回来的内存realloc.

您需要返回指针或通过orig_str引用传递.

另外(如注释中所指出的)您需要realloc(orig_str, req_space + 1);为null终止符留出空间.


您的代码有一些低效的逻辑,与此固定版本相比:

bool append(char **p_orig_str, const char *append_str)
{
    // no action required if appending an empty string
    if ( append_str[0] == 0 )
         return true;

    size_t orig_len = strlen(*p_orig_str);
    size_t req_space = orig_len + strlen(append_str) + 1;
    char *new_str = realloc(*p_orig_str, req_space);

    // resize success.. 
    if(new_str == NULL)
    {
        fprintf(stderr, "Couldn't reallocate memory\n");
        return false;
    }

    *p_orig_str = new_str;
    strcpy(new_str + orig_len, append_str);
    return true;
}
Run Code Online (Sandbox Code Playgroud)