我编写了一个可变参数 C 函数,其任务是为缓冲区分配所需的内存,然后在该缓冲区中 sprintf 给该函数的参数。但我看到它有一种奇怪的行为。它只工作一次。如果我对此函数有两次调用,则会出现段错误。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
char *xsprintf(char * fmt, ...)
{
va_list ap;
char *part;
char *buf;
size_t len = strlen(fmt)+1;
va_start(ap, fmt);
while (part = va_arg(ap, char *))
len += strlen(part);
va_end(ap);
buf = (char*) malloc(sizeof(char)*len);
va_start(ap, fmt);
vsprintf(buf, fmt, ap);
va_end(ap);
return buf;
}
int main(int argc, const char *argv[])
{
char *b;
b = xsprintf("my favorite fruits are: %s, %s, and %s", "coffee", "C", "oranges");
printf("size de buf is %d\n", strlen(b)); //this works. After it, it segfaults.
/*
free(b);
b = NULL;
*/
b = xsprintf("my favorite fruits are: %s, %s, and %s", "coffee", "C", "oranges");
printf("size de buf is %d\n", strlen(b));
printf("%s", b);
return 0;
}
这是这个程序的输出:
size de buf is 46
[1] 4305 segmentation fault ./xsprintftest
难道我做错了什么?我不应该va_start
在一个函数中多次使用吗?你有其他选择吗?非常感谢!:)