【C言語】
ダングリングポインタ
(Dangling Pointer)の見つけ方

warning: Use of memory after it is freed

警告:無効な領域を指しているポインタ

[clang –analyze]


■解放済み領域を指すダングリングポインタ

#include    <stdio.h>
#include    <stdlib.h>
#include    <string.h>
char *fullpath(char *path,char *file);
//解放済み領域を指すダングリングポインタ
int main(void){
    char    *cp = malloc(128);
    if(cp == NULL){
        perror(NULL);
        exit(1);
    }
    strcpy(cp,__func__);
    free(cp);//解放済み
    puts(cp);//Dangling Pointer
    puts(fullpath("root","file.c"));
}

■終了した自動変数領域を指すダングリングポインタ

char *fullpath(char *path,char *file){
    char    buf[128];
    char    *ptr = buf;
    sprintf(ptr,"%s/%s",path,file);
    return  ptr;//Dangling Pointer:自動変数終了    
}

この問題は以下のオプションで検出できます。
clang –analyze