3 ms·
edit: parent didn't originally - 1 from sizeof. Except you just failed to null-terminate your string, good job at proving the truth of the article :) #inclu
by btbuilder 14y ago
edit: parent didn't originally - 1 from sizeof.
Except you just failed to null-terminate your string, good job at proving the truth of the article :)
#include <stdio.h>
#include <string.h>
int main(void)
{
char buffer[5] = {0};
strncpy(buffer, "This is a long string", sizeof(buffer));
printf("%s\n", buffer);
}
$ ./test
This ^`gh?
- primitur 14y ago$ cat /tmp/t.c #include <stdio.h> #include <string.h> char buffer[5] = {0}; int main(int argc, char argv) { strncpy(buffer, "This is a long string", sizeof buffer - sizeof buffer[0]); printf("The string: [%s] The len: %ld\n", buffer, sizeof buffer); } $ /tmp/t The string: [This] The len: 5 $ gcc -v Using built-in specs. COLLECT_GCC=gcc COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/4.6/lto-wrapper Target: x86_64-linux-gnu Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 4.6.3-1ubuntu5' --with-bugurl=file:///usr/share/doc/gcc-4.6/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.6 --enable-shared --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.6 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --enable-plugin --enable-objc-gc --disable-werror --with-arch-32=i686 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu Thread model: posix gcc version 4.6.3 edit: oops. Coverage before Coffee!
- Aloisius 14y agoThe string: [This ] The len: 5 Doesn't it bother you that your 5 character long buffer that is supposed to be terminated by a null happens to have 5 characters in it "[This ]" instead of 4 visible "[This]"? Your memory just happens to have a null 6 bytes after the pointer.
- dibbit 14y agoRun the code and see for yourself, parent fixed it.