sprintf 的意外行为

Unexpected behavior with sprintf

我正在编写一个程序,但遇到一个非常奇怪的问题。

char *abs_alg *iterator *test_case;
sprintf(abs_alg, "%s/data_root/projects/PROJ-%s/proj/src/%sAbsAlgorithm.cpp", getenv(ALGATOR_ROOT), argv[2], argv[2]);
sprintf(iterator, "%s/data_root/projects/PROJ-%s/proj/src/%sTestSetIterator.cpp", getenv(ALGATOR_ROOT), argv[2], argv[2]);
sprintf(test_case, "%s/data_root/projects/PROJ-%s/proj/src/%sTestCase.cpp", getenv(ALGATOR_ROOT), argv[2], argv[2]);

在最后一行,我收到运行时错误: 线程 1:EXC_BAD_ACCESS(代码=1,地址=0x3)

前两个 sprintf 函数运行良好,但最后一个函数运行不正常。另外,如果我将 *char test_case 更改为 char test_case[500],那么我在程序中的这一行之前会出错:

char *lib_dir;
sprintf(lib_dir, "%s/data_root/projects/PROJ-%s/lib/", getenv(ALGATOR_ROOT), argv[2]);

我正在使用 XCode-beta 7.0。

g++ --version
Configured with: --prefix=/Applications/Xcode-beta.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode-beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/c++/4.2.1
Apple LLVM version 7.0.0 (clang-700.0.53.3)
Target: x86_64-apple-darwin15.0.0
Thread model: posix

我一整天都在尝试解决这个问题,但没有成功。如果能得到任何帮助,我将不胜感激。

sprintf 不会为返回的字符串分配内存(在您的情况下为 lib_dir)。

假设答案最多为 256 个字符你应该写:

char lib_dir[256];
sprintf(lib_dir, "%s/data_root/projects/PROJ-%s/lib/", getenv(ALGATOR_ROOT), argv[2]);

如果您不确定大小限制,可以查看有关 sprintf() with automatic memory allocation 的问题。