C:字符串操作添加更多字符而不会导致缓冲区溢出

Fra*_*lea 1 c string

在CI中我的一个字符串中有一条路径

/home/frankv/
Run Code Online (Sandbox Code Playgroud)

我现在想要添加此文件夹中包含的文件名 - 例如file1.txt file123.txt等.

宣布我的变量是这样的

char pathToFile[strlen("/home/frankv/")+1]
Run Code Online (Sandbox Code Playgroud)

要么

char *pathToFile = malloc(strlen("/home/frankv/")+1)
Run Code Online (Sandbox Code Playgroud)

我的问题是我不能简单地添加更多字符,因为它会导致缓冲区溢出.另外,如果我不知道文件名会有多长,我该怎么办?

我已经习惯了PHP lazy $ string1.$ string2 ..在C中最简单的方法是什么?

Kei*_*son 6

如果您已分配缓冲区malloc(),则可以使用realloc()它来扩展它:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
    char *buf;
    const char s1[] = "hello";
    const char s2[] = ", world";

    buf = malloc(sizeof s1);
    strcpy(buf, s1);

    buf = realloc(buf, sizeof s1 + sizeof s2 - 1);
    strcat(buf, s2);

    puts(buf);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

注意:我省略了错误检查.你不应该.始终检查是否malloc()返回空指针; 如果确实如此,采取一些纠正措施,即使它只是终止程序.同样地realloc().如果您希望能够从realloc()失败中恢复,请将结果存储在临时中,这样您就不会破坏原始指针.