我正在阅读“21 世纪 C”(第一版)一书,并找到了一个有趣的程序,它使用 asprintf 来获取字符串,而无需使用 malloc /size of 来获取字符串长度或空间分配。请阅读同一本书中的附图以了解上下文。以下程序也来自书中。程序编译运行,而不是从键盘输入字符串,而是得到以下消息。问题是:为什么程序不从 keboard 获取字符串输入,而是显示长(不寻常)错误消息?
#define _GNU_SOURCE // stdio.h to include asprintf
#include <stdlib.h>
#include <stdio.h>
void get_strings(char const *in) {
char *cmd;
asprintf(&cmd, "strings %s", in);
if (system(cmd))
fprintf(stderr, "Something went Wrong %s.\n", cmd);
free(cmd);
}
int main(int argc, char **argv) {
get_strings(argv[0]);
//return 0;
}
运行程序时输出为:
/lib64/ld-linux-x86-64.so.2
libc.so.6
__stack_chk_fail
asprintf
stderr
system
fprintf
__libc_start_main
free
__gmon_start__
GLIBC_2.4
GLIBC_2.2.5
UH-X
AWAVA
AUATL
[]A\A]A^A_
strings %s
Something went Wrong %s.
;*3$"
GCC: (Ubuntu 5.3.1-14ubuntu2) 5.3.1 20160413
crtstuff.c
__JCR_LIST__
deregister_tm_clones
__do_global_dtors_aux
completed.7585
__do_global_dtors_aux_fini_array_entry
frame_dummy
__frame_dummy_init_array_entry
get_strings.c
__FRAME_END__
__JCR_END__
__init_array_end
_DYNAMIC
__init_array_start
__GNU_EH_FRAME_HDR
_GLOBAL_OFFSET_TABLE_
__libc_csu_fini
free@@GLIBC_2.2.5
_ITM_deregisterTMCloneTable
_edata
__stack_chk_fail@@GLIBC_2.4
system@@GLIBC_2.2.5
get_strings
__libc_start_main@@GLIBC_2.2.5
__data_start
fprintf@@GLIBC_2.2.5
__gmon_start__
__dso_handle
_IO_stdin_used
__libc_csu_init
__bss_start
asprintf@@GLIBC_2.2.5
main
_Jv_RegisterClasses
__TMC_END__
_ITM_registerTMCloneTable
stderr@@GLIBC_2.2.5
.symtab
.strtab
.shstrtab
.interp
.note.ABI-tag
.note.gnu.build-id
.gnu.hash
.dynsym
.dynstr
.gnu.version
.gnu.version_r
.rela.dyn
.rela.plt
.init
.plt.got
.text
.fini
.rodata
.eh_frame_hdr
.eh_frame
.init_array
.fini_array
.jcr
.dynamic
.got.plt
.data
.bss
.comment
------------------
(program exited with code: 0)
Press return to continue
**I running it on Linux Mint 18. GCC version -5.3.1
Build setting - gcc -Wall -c "%f"
Compile - gcc -Wall -o "%e" "%f"**