2015-07-20 21 views
0

我正在編寫一個程序,我有一個很奇怪的問題。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函數都工作得很好,但是這最後一個ISN 「T。另外,如果我改變*字符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-β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 

我一直在努力解決這一整天,但沒有成功。我將不勝感激任何幫助。

+0

'abs_alg','lib_dir'必須以某種方式預先分配。 – AlexD

回答

1

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這個問題。

+0

工程就像一個魅力!謝謝! :) – golobich