写ptr =&i是否合法; 在C?

msc*_*msc -5 c malloc gcc pointers c11

我已经使用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;
}
Run Code Online (Sandbox Code Playgroud)

显示的输出10.

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

ptr = &i;用C语写是否合法?

编辑:

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

use*_*738 6

这没什么不合法的.它只是造成内存泄漏.在这个程序实例中,您永远不会使用分配的内存.

你可能做了什么?

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

  • 你可以存储该地址.

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

    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;
    
    Run Code Online (Sandbox Code Playgroud)