Stack Exchange
Unexpected behavior with sprintf
I am writing a program and I have a very weird issue.
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]);

In last row, I get runtime error:
Thread 1: EXC_BAD_ACCESS (code=1, address=0x3)
First two sprintf function are working just fine, but this last one isn't. Also, if I change *char test_case to char test_case[500], then I get error before in program in this line:
char *lib_dir;
sprintf(lib_dir, "%s/data_root/projects/PROJ-%s/lib/", getenv(ALGATOR_ROOT), argv[2]);

I am using 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

I've been trying to fix this all day but without success. I would appreciate any help I can get.

abs_alg, lib_dir have to be pre-allocated somehow.

sprintf does not allocate memory for the returning string (lib_dir in your case).
Assuming the answer is 256 characters at most you should write:
char lib_dir[256];
sprintf(lib_dir, "%s/data_root/projects/PROJ-%s/lib/", getenv(ALGATOR_ROOT), argv[2]);

If you're not sure about the size limit, you can check out this question regarding sprintf() with automatic memory allocation.

Works like a charm! Thank you! :)
