【发布时间】:2019-12-30 17:59:49
【问题描述】:
我有以下程序:我的程序编译良好,并给出如下所述的输出。我对底部列出的输出有一些疑问。 ****************************************************** *****************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *p = malloc(sizeof(char));
char *q = malloc(sizeof(char));
printf("address of p = %p \n", p); A
printf("address of q = %p \n", q); B
strcpy(p, "abcdefghijklmnopqrstuvwxyz123456789abcdefghijklmnopqrstuvwxyz");
printf("Value in P : %s \n", p); C
printf("Value in q : %s\n", q); D
printf("string length of P : %d \n", strlen(p)); E
printf("string lenght of q : %d\n", strlen(q)); F
return 0;
}
===OUTPUT ==
address of p = 0xbbf010
address of q = 0xbbf030
Value in P : abcdefghijklmnopqrstuvwxyz123456789abcdefghijklmnopqrstuvwxyz
Value in q : 789abcdefghijklmnopqrstuvwxyz
string length of P : 61
string lenght of q : 29
=====输出结束==
问题:
1.为什么p和q的地址相差32字节。我只为 P 分配了 1 个字节。连续malloc 之间如何自动产生 32 个字节的差异?
2. 我没有NULL 终止我的字符串。 printf如何检测到\0终止?
3. 如果没有\0 终止,strlen 如何也能正常工作?
【问题讨论】:
-
strcpy(p, "abcdefghijklmnopqrstuvwxyz123456789abcdefghijklmnopqrstuvwxyz");调用 未定义的行为 - 你从这段代码得到的任何结果都是没有意义的 -
char *p = malloc(sizeof(char));= 您分配了 1 个字节并稍后将更长的字符串复制到该地址,因此您正在覆盖随机内存位置(@UnholySheep)并且地址相差超过 1 个字节,因为内存通常分配在对齐的地址上。它的对齐方式因编译器和系统而异,但通常对齐在 4、8、16 或 32 字节边界上。 -
零终止是由strcpy引起的。查一下:-)
-
@infinite 字符可以从任何字节地址开始,但 malloc 始终分配对齐的存储空间。它选择的对齐方式是未定义的。
-
"abcdefghijklmnopqrstuvwxyz123456789abcdefghijklmnopqrstuvwxyz" 有一个空值,strcpy 复制了这个空值。
标签: c string char null-terminated