相关疑难解决方法(0)

当使用free()释放内存时,为什么指针指向的内容没有改变?

在动态内存分配方面,我是新手.当我们释放内存时,使用void free(void *ptr)内存被释放,但指针的内容不会被删除.这是为什么?最新的C编译器有什么不同吗?

c malloc free pointers memory-management

3
推荐指数
1
解决办法
142
查看次数

realloc()悬空指针和未定义的行为

当你释放内存时,指向内存的指针会发生什么?他们立即变得无效吗?如果他们以后再次有效会怎么样?

当然,指针变为无效然后再次变为"有效"的通常情况是将其他对象分配到之前使用的内存,如果使用指针访问内存,那么这显然是未定义的行为.悬空指针内存覆盖了第1课,差不多.

但是如果内存再次对同一个分配有效呢?只有一种标准方式可以实现:realloc().如果你有一个指向malloc()偏移量'd存储块内某处的指针> 1,那么使用realloc()缩小块到小于你的偏移量,显然你的指针变得无效.如果你再次使用realloc()增长块至少覆盖悬空指针指向的对象类型,并且在任何情况下都没有realloc()移动内存块,悬空指针是否再次有效?

这是一个极端的案例,我真的不知道如何解释C或C++标准来解决它.以下是显示它的程序.

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

int main(void)
{
    static const char s_message[] = "hello there";
    static const char s_kitty[] = "kitty";

    char *string = malloc(sizeof(s_message));
    if (!string)
    {
        fprintf(stderr, "malloc failed\n");
        return 1;
    }

    memcpy(string, s_message, sizeof(s_message));
    printf("%p %s\n", string, string);

    char *overwrite = string + 6;
    *overwrite = '\0';
    printf("%p %s\n", string, string);

    string[4] = '\0';
    char *new_string = …
Run Code Online (Sandbox Code Playgroud)

c pointers realloc undefined-behavior dangling-pointer

1
推荐指数
1
解决办法
828
查看次数