gpt4 book ai didi

c - malloc...意外行为c编程

转载 作者:太空宇宙 更新时间:2023-11-04 06:08:32 25 4
gpt4 key购买 nike

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

void foo( char ** ptr)
{
*ptr = malloc(0); // allocate some memory**
strcpy( *ptr, "Hello World");
}

int main()
{
char *ptr = 0;
// call function with a pointer to pointer
foo( &ptr );
printf("%s\n", ptr);
// free up the memory
free(ptr);

return 0;
}

它也在运行

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

void foo( char ** ptr)
{
*ptr = malloc(11); // allocate some memory
strcpy( *ptr, "Hello World");
}

int main()
{
char *ptr = 0;
// call function with a pointer to pointer
foo( &ptr );
printf("%s\n", ptr);
// free up the memory
free(ptr);

return 0;
}

将 malloc 更改任意数量...它始终在运行。这怎么可能????Hello World 有 12 个字符,所以怎么可能在 0、12、8 中运行,任何数字。

最佳答案

你遇到了 C 不做任何边界检查的事实。因此,您复制到 malloc 内存的副本超出了分配范围,并在随后的任何内存上“涂鸦”。结果未定义。它可能会工作,可能会崩溃,它可能会给你一杯咖啡。你不知道。

顺便说一下,这种错误会导致缓冲区溢出攻击。

关于c - malloc...意外行为c编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5177152/

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