Malloc printf开头有奇怪的字符

时间:2021-07-10 00:26:17

I am currently learning C and got stuck on this strange error. What strange is that this error doesn't occur on one compiler, but does occur on two others. Given that I am rather new to malloc, I figure that maybe I did something I shouldn't have.

我目前正在学习C并且遇到了这个奇怪的错误。奇怪的是,这个错误不会在一个编译器上发生,但确实发生在另外两个编译器上。鉴于我对malloc很新,我想也许我做了一些我不应该做的事情。

Here is the code I am having trouble with:

这是我遇到的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char* int_to_binary(unsigned int x)
{
    char *str = (char *) malloc(sizeof(char)*9);

    int z;
    for (z = 128; z > 0; z >>= 1)
    {
        strcat(str, ((x & z) == z) ? "1" : "0");
    }
    return str;
}

int main()
{
    printf("Testing: %s\n", int_to_binary(1));
    return 0;
}

I compile this file on a linux platform and got the following output:

我在linux平台上编译这个文件并得到以下输出:

Testing: 00000001

测试:00000001

But on a C compiler on Windows and on codepad.org, I got the following output:

但是在Windows和codepad.org上的C编译器上,我得到了以下输出:

Testing: ����������00000001

测试: 00000001

I don't understand what is causing the extra characters before the cstring.

我不明白是什么导致cstring之前的额外字符。

1 个解决方案

#1


2  

You can't strcat() to an uninitialized buffer, it expects its first parameter to be nul terminated. Also using strcat() like that is a bad idea, you should use pointer artihmetics to append the character and nul terminate str in order to pass it to printf().

你不能strcat()到一个未初始化的缓冲区,它期望它的第一个参数是nul终止。同样使用strcat()是一个坏主意,你应该使用指针artihmetics来附加字符和nul终止str以便将它传递给printf()。

char *ptr;

ptr = str;
for (z = 128 ; z > 0 ; z >>= 1, ptr++)
    *ptr = ((x & z) == z) ? '1' : '0';
*ptr = '\0';

#1


2  

You can't strcat() to an uninitialized buffer, it expects its first parameter to be nul terminated. Also using strcat() like that is a bad idea, you should use pointer artihmetics to append the character and nul terminate str in order to pass it to printf().

你不能strcat()到一个未初始化的缓冲区,它期望它的第一个参数是nul终止。同样使用strcat()是一个坏主意,你应该使用指针artihmetics来附加字符和nul终止str以便将它传递给printf()。

char *ptr;

ptr = str;
for (z = 128 ; z > 0 ; z >>= 1, ptr++)
    *ptr = ((x & z) == z) ? '1' : '0';
*ptr = '\0';