十进制转二进制C程序随机追加异常字符串问题咨询
Hey there, let's break down why that odd " ttime__vdso_get " string is popping up at the end of your binary output, and how to fix it.
核心原因:未初始化的数组与缺失的字符串终止符
- Your
char bin[64];is a local variable, and in C, local variables aren't automatically initialized to 0. That means the array starts filled with leftover garbage data from whatever was in that memory space before. - The
printf("%s")function works by printing characters until it hits a'\0'(null terminator) — the standard end marker for C strings. Your code writes binary digits into the array, but it never adds this critical'\0'. So printf keeps reading past your valid binary digits, dumping random memory content until it stumbles on a'\0'somewhere. That's where that weird string comes from.
快速修复方案
There are two straightforward ways to fix this, plus a bonus edge case handling:
1. 初始化数组时直接清零
The simplest fix is to initialize the entire array to '\0' when you declare it. This ensures any unused positions in the array are already valid terminators:
#include <stdio.h> #include <string.h> int main() { printf("Number (decimal): "); int no; scanf("%d", &no); char bin[64] = {0}; // 初始化整个数组为'\0' while (no > 0) { for (int i = strlen(bin); i > 0; i--) { bin[i] = bin[i - 1]; } int bit = no % 2; char digit = bit + '0'; bin[0] = digit; no /= 2; } printf("%s\n", bin); return 0; }
2. 手动跟踪长度并添加终止符
If you don't want to initialize the whole array, you can track how many binary digits you've written, then explicitly add the '\0' at the right position:
#include <stdio.h> #include <string.h> int main() { printf("Number (decimal): "); int no; scanf("%d", &no); char bin[64]; int digit_count = 0; // 记录已写入的二进制位数 while (no > 0) { // 移位时用digit_count代替strlen,更高效 for (int i = digit_count; i > 0; i--) { bin[i] = bin[i - 1]; } int bit = no % 2; char digit = bit + '0'; bin[0] = digit; digit_count++; no /= 2; } bin[digit_count] = '\0'; // 手动添加终止符 printf("%s\n", bin); return 0; }
Bonus:处理输入0的边界情况
Right now, if you input 0, your program will output nothing (since the loop doesn't run). Adding a quick check fixes this:
if (no == 0) { strcpy(bin, "0"); }
Stick this right after the scanf line, and your program will correctly output "0" for that case.
验证修改
After making either of these changes, your program will stop dumping random memory content — the output will only show the correct binary string, no extra garbage attached.
内容的提问来源于stack exchange,提问作者JackHasaKeyboard

