gpt4 book ai didi

c++ - 调用 vsnprintf 时的核心转储

转载 作者:行者123 更新时间:2023-11-30 00:37:47 24 4
gpt4 key购买 nike

我在 ubuntu 12.04 上,使用 uname -a:Linux lu057801 3.2.0-31-generic#50-Ubuntu SMP Fri Sep 7 16:16:45 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux

g++ --版本:Linux lu057801 3.2.0-31-generic#50-Ubuntu SMP Fri Sep 7 16:16:45 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux

我在调用 vsnprintf 时得到一个核心转储。以下是产生问题的完整代码:

// compile: g++ -g -o test vsnprintf_test.c

#include <stdarg.h>
#include <stdio.h>
#include <string>

void vout(char *string, char *fmt, ...);
char fmt1 [] = "%s %s %s\n";

size_t snprintf_1(char* buffer, const size_t bufSize, const char* format, ...);
size_t vsnprintf_1(char* buffer, const size_t bufSize, const char* format, va_list args);

int main(void)
{
char * format = "%s";
char buffer[] = "/var/tmp\0"; //char * buffer = "/var/tmp\0";
int bufSize=sizeof(buffer); //int bufSize=11;
snprintf_1(buffer, bufSize, format);
}


size_t snprintf_1(char* buffer, const size_t bufSize, const char* format, ...)
{
va_list args;
va_start(args, format);
size_t rc = vsnprintf_1(buffer, bufSize, format, args);
va_end(args);
return rc;
}


size_t vsnprintf_1(char* buffer, const size_t bufSize, const char* format, va_list args)
{
int rc = 0;
rc = vsnprintf(buffer, bufSize, format, args);
}

编译为:g++ -g -o test vsnprintf_test.c 并运行会给我以下回溯:

(gdb) run
Starting program: /home/mafunk/software/MattsSnippets/test

Program received signal SIGSEGV, Segmentation fault.
_IO_vsnprintf (string=0x400738 "/var/tmp", maxlen=<optimized out>, format=0x400730 "%s", args=0x7fffffffe0b0) at vsnprintf.c:118
118 vsnprintf.c: No such file or directory.
(gdb) bt
#0 _IO_vsnprintf (string=0x40072f "/var/tmp", maxlen=<optimized out>, format=0x40072c "%s", args=0x7fffffffe0b0) at vsnprintf.c:118
#1 0x0000000000400639 in vsnprintf_1 (buffer=0x40072f "/var/tmp", bufSize=11, format=0x40072c "%s", args=0x7fffffffe0b0)
at vsnprintf_test.c:36
#2 0x00000000004005f2 in snprintf_1 (buffer=0x40072f "/var/tmp", bufSize=11, format=0x40072c "%s") at vsnprintf_test.c:27
#3 0x0000000000400541 in main () at vsnprintf_test.c:19

我想我不确定为什么会这样。任何帮助将不胜感激。

最佳答案

段错误是因为您尝试写入的目标是字符串文字

此外,调用 snprintf_1(buffer, bufSize, format); 传递了一个 "%s" 格式字符串,但没有其他参数。格式字符串需要一个额外的 char * 参数,并且代码将在调用堆栈上读取您未提供的字符串指针的随机内存。

关于c++ - 调用 vsnprintf 时的核心转储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12819136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com