#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>	/** for strdup() */

#define SUCCEED		0
#define FAIL		-1

#define FILENAME	"/etc/passwd"

static int	get_dir_names(const char *filename, char **pathname)
{
	char resolved_path[PATH_MAX + 1];	/* allocated on stack */

	if (NULL == (*pathname = realpath(filename, resolved_path)))
                return FAIL;

	/*  *pathname = strdup(*pathname);  */       /* <---- uncomment this line to fix bug */

        return SUCCEED;		/* 'resolved_path' goes out of scope, 'pathname' is now a stale pointer! */
}

int main()
{
	char	*pathname = NULL;

        if (SUCCEED != get_dir_names(FILENAME, &pathname))
	{
		printf("get_dir_names() returned error\n");
		return 1;
	}

	printf("realpath is (crash is possible):\n");
	printf("%s\n", pathname);

	printf("freeing memory, crash is possible\n");
        free(pathname);	/* 'pathname' (a stale pointer to a stack-allocated (time ago) buffer) is passed to 'free() */
	printf("memory free did not cause crash\n");

	return 0;
}
