c - 具有可变函数的段错误

标签 c

我已经尝试调试了一个小时,但我失败了。我有一个可变参数函数 set_buffer,它接收缓冲区以将输入字符串设置为

void set_buffer(char *buf, int num_str, ...) { // destructively sets buffer with the strings provided, in the order they are provided. Must provide number of arguments so function knows where to stop.
    size_t length = sizeof(buf) / sizeof(*buf); // strlen() fails because it depends on the null terminator...
    printf("length: %d\n", length);
    va_list args;
    va_start(args, num_str); // va_start takes on the NAME of the last known parameter in the function to determine where to start taking in optional arguments
    for (int i = 0, offset = 0; i < num_str && offset < length; ++i) {
        char *str = va_arg(args, char *);
        printf("length of str: %d\n", strlen(str)); // SEG FAULT ERROR
        offset += snprintf(buf+offset, strlen(str)+1, "%s", str); // I must be adding too much of an offset, resulting in a seg fault
        if (i != (num_str - 1)) {
            //offset -= 1;
        }
    }
    va_end(args);
}

我怀疑这可能与从 va_list args 中错误地获取参数有关。

最佳答案

sizeof(buf) / sizeof(*buf)仅在 buf 时有效具有数组类型,而不是指针。根据您使用的是 32 位还是 64 位目标,它将计算为常量 4 或 8。

您需要传递一个指定可用缓冲区大小的参数。

这并不完全指向崩溃,因为结果仅用于 offset < length测试。 (顺便说一句,这是不正确的;您应该使用 length 将指定的空间限制为 snprintf。)要查看出现了什么问题,我们需要一个完整的、独立的测试用例。

关于c - 具有可变函数的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22108423/

相关文章:

c - 如何将 regexec 与内存映射文件一起使用?

c - 使用指针填充二维数组

c - 是否可以将 va_list 用于树结构中的子节点?

将 MIPS32 转换为 C : adding an array's base address to arbitrary value and its meaning

c - 在替换文本之前使用 # 时不正确地终止宏调用

c - Ubuntu 用法错误

c - MSVCRT:sin、cos等的实现(源码)在哪里?

显示链表函数的c程序

我们可以将 va_arg 与 union 一起使用吗?

c - C 中结构中的矩阵