为什么分配关于C中的一个字节的工作大量? [英] Why does assigning a large number in one byte work in C?

查看:149
本文介绍了为什么分配关于C中的一个字节的工作大量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int *ptr = malloc(sizeof(char));

*ptr = 100000;

printf("%d\n", *ptr); // 100000

不应该只在一个字符,即1个字节分配足够的内存?因此,不应该数最多为255?

Shouldn't that only allocate enough memory for a char, i.e. 1 byte? Therefore shouldn't the largest number be 255?

它如何仍然打印 100000

感谢您的答案。如果它覆盖的下一个字节,如何C,那么知道这个数字大于一个字节,而不是仅仅看在第一个字节?

Thanks for the answers. If it overwrites the next bytes, how does C then know that this number is larger than one byte, and not just look in the first byte?

推荐答案

由于C有内存没有范围检查。它分配一个字节,然后通过该指针你的任务覆盖它和接下来的三个字节。如果你在第一个的malloc之后分配的内存另一位,但在分配之前,你可能有堆的覆盖部分(取决于你的malloc是如何工作的)。

Because C has no range-checking of memory. It allocates a byte, and then your assignment via the pointer overwrites it and the next three bytes. If you had allocated another bit of memory right after the first malloc, but before the assignment, you might have overwritten part of the heap (depending on how your malloc works).

这也是为什么指针可以在C非常危险的。

This is why pointers can be very dangerous in C.

格式的语句(加上变量的类型)的%d个会告诉你正在寻找一个int编译器,并访问所有四个字节。

The %d in the format statement (plus the type of the variable) tells the compiler you are looking at an int, and accesses all four bytes.

请注意,如果你真的有值分配给一个字符,例如字符* PTR; * PTR = 100000;

Note that if you really had assigned the value to a char, e.g. char *ptr; *ptr = 100000;

然后用一些编译器(假设无格式字符作为签署,但默认处理),它会打印出-96,而不是255(或127)。这是因为编译器不会自动限制值,可以(在unsigned char类型的符号字符127,255),以符合最高的价值,而是它只是溢出。大多数编译器会抱怨你想分配一个溢出变量一个恒定值。

then with some compilers (and assuming plain char is treated as signed but default) it would have printed out -96, not 255 (or 127). This is because the compiler doesn't automatically limit the value to the highest value that can fit (127 in a signed char, 255 in an unsigned char), but instead it just overflows. Most compilers will complain that you are trying to assign a constant value that overflows the variable.

的原因,它是-96,是100000%256 160,但作为一个char签署被输出为 - (256-160)

The reason it is -96, is that 100000 % 256 is 160, but as a signed char it is output as -(256-160).

这篇关于为什么分配关于C中的一个字节的工作大量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆