gpt4 book ai didi

Char 指针 NULL 终止和内存分配

转载 作者:行者123 更新时间:2023-11-30 18:33:03 25 4
gpt4 key购买 nike

我有以下程序:我的程序编译良好并给出如下所示的输出。我对底部列出的输出有一些疑问。****************************************************** ******************************/

#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. strlen 如何在没有 \0 终止的情况下也正常工作?

最佳答案

  1. Why there is a difference of 32 bytes between address of p and q. I have allocated 1 byte only for P. How automatically 32 byte difference between successive malloc?

因为这就是您的实现选择的方式。任何两次 malloc() 调用的返回值之间没有任何特定关系,甚至是像您这样的连续调用。

实际上,C 实现倾向于以多字节粒度分配内存,即使请求的大小较小,这就是您所观察到的。这绝对并不意味着可以访问超出您明确请求的范围的内存。

  1. I have not NULL terminated my Strings. How printf detecting the \0 termination?
  2. How strlen is also working fine without a \0 termination?

谁说你的字符串没有终止?字符串文字当然是。除此之外,您还可以通过超出 p 指向的已分配空间的范围来产生未定义的行为,因此任何事情都可能发生。

如果您想推测 UB,那么您可能会根据观察到的输出猜测 strcpy 将字节从源字符串复制到从 *p 开始的内存中,继续遍历该字节和 *q 之间的所有未分配字节,并继续进入 *q 之外的未分配空间,直到最终复制 nul 字节。然后,您可能会猜测 printfstrlen 类似地从一个或另一个起点读取到未分配的区域。

这可能会或可能不会准确地描述实际发生的情况,并且在任何情况下,您都不应该将观察到的结果解释为此类程序行为是可预测的或可接受的。特别是,此类行为通常会损坏分配器的元数据,当您尝试释放已分配的空间或分配其他空间时,可能会出现这种情况。

关于Char 指针 NULL 终止和内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59534956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com