Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

不要被别人的 memset(buf, -1, sizeof(buf)) 迷惑了 #2

Open
district10 opened this issue Aug 11, 2016 · 0 comments
Open

不要被别人的 memset(buf, -1, sizeof(buf)) 迷惑了 #2

district10 opened this issue Aug 11, 2016 · 0 comments

Comments

@district10
Copy link
Owner

district10 commented Aug 11, 2016

有文件 test.c

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

int main()
{
    int m[2];
    printf( "sizeof(m): %lu\n", sizeof(m) );

    memset( m, -1, sizeof(m) );
    printf( "after memset(m,   -1, sizeof(m)): %20d (0x%08x), %20d (0x%08x)\n", m[0], m[0], m[1], m[1] );

    memset( m,  1, sizeof(m) );
    printf( "after memset(m,    1, sizeof(m)): %20d (0x%08x), %20d (0x%08x)\n", m[0], m[0], m[1], m[1] );

    memset( m, 0xFF, sizeof(m) );
    printf( "after memset(m, 0xFF, sizeof(m)): %20d (0x%08x), %20d (0x%08x)\n", m[0], m[0], m[1], m[1] );

    memset( m, 0xA5, sizeof(m) );
    printf( "after memset(m, 0xA5, sizeof(m)): %20d (0x%08x), %20d (0x%08x)\n", m[0], m[0], m[1], m[1] );
}

编译运行

$ gcc test.c -o test
$ ./test
sizeof(m): 8
after memset(m,   -1, sizeof(m)):                   -1 (0xffffffff),                   -1 (0xffffffff)
after memset(m,    1, sizeof(m)):             16843009 (0x01010101),             16843009 (0x01010101)
after memset(m, 0xFF, sizeof(m)):                   -1 (0xffffffff),                   -1 (0xffffffff)
after memset(m, 0xA5, sizeof(m)):          -1515870811 (0xa5a5a5a5),          -1515870811 (0xa5a5a5a5)

所以,要小心了。别人用 memset(buf, -1, sizeof(buf)) 来初始化 buf,你用 -2 可不是 -2 啊!

这涉及到 two's compliment 编码。


另一个不符合直觉的是 int buf[50] = { 0 }; 确实会把所有元素初始化为 0,但是 int buf[50] = { 3 }; 只回初始化第一个元素为 3,其它都是 0……至少在我的 gccg++ 上都是如此。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant