关于C中unsigned char *的奇怪问题

所以我有一个方法返回一个unsigned char *

unsigned char* someMethod(num)
unsigned short num;
{
    //do some stuff with num and change values of a
    unsigned char * a = (unsigned char*) malloc(4);
    printf("a0 is %x\n",a[0]);
    printf("a1 is %x\n",a[1]);
    printf("a2 is %x\n",a[2]);
    printf("a3 is %x\n",a[3]);
    return a;
}

当我调用someMethod(128)时:

unsigned char* s = someMethod(128);
printf("s0 is %x\n",s[0]);
printf("s1 is %x\n",s[1]);
printf("s2 is %x\n",s[2]);
printf("s3 is %x\n",s[3]);

它会打印出来

a0 is 30
a1 is 1
a2 is 31
a3 is 30
s0 is 30
s1 is 14
s2 is ffffff9d
s3 is 0

因为我指定了s = someMethod(128),所以对我来说没有任何意义. a和s不应该有相同的值吗?!?
任何帮助表示赞赏.谢谢!

最佳答案 关于@ gl3829的评论,我会选择

unsigned char *a = malloc(4 * sizeof(*a))

这样尺寸“自动”正确.

更重要的是,我认为一个问题是,在someMethod中,您在实际分配任何内容之前打印出已分配数组中的值.这会调用未定义的行为,并允许产生任何结果.在打印之前尝试存储一些东西.

要以十六进制打印无符号字符,正确的格式说明符为%hhx.使用错误的说明符也可以调用未定义的行为.

点赞