写 ptr = &i; 合法吗?在C?

Is it legal to write ptr = &i; in C?

我使用 gcc prog.c -Wall -Wextra -pedantic -std=gnu11 命令在 GCC 上编译了以下代码。它不会产生任何警告或错误。

代码:

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

int main() 
{
    int i = 10;
    int *ptr = malloc(1);

    ptr = &i; // is it legal?

    printf("%d\n", *ptr);
    return 0;
}

10 的显示输出。

这里,使用malloc函数为ptr指针分配动态内存,然后ptr保存i变量的地址。

用 C 写 ptr = &i; 合法吗?

编辑:

那么,编译器是否可以生成有关内存泄漏的警告?

没有什么违法的。它只是造成内存泄漏。您将永远无法在该程序的这个实例中使用分配的内存。

你可能做了什么?

  • 如果不需要,根本不分配内存。

  • 您本可以存储该地址。

  • 在覆盖指针中存储的内容之前,您可以释放该内存。

    int i = 10;
    int *ptr = malloc(1*sizeof(int));
    int *stored;
    if(ptr == NULL){
        fprintf(stderr,"Error in Malloc");
        exit(1);
    }
    stored = ptr; // avoiding memory leak.
    ptr = &i;  
    free(stored);
    printf("%d\n", *ptr);
    return 0;