I have to memory map a file if there is not already one for that file. The code I provided is not working. I am calling this function twice from another file and each time it is creating different mmapPtr.
char *mmapPtr;
void MemoryMapFile()
{
int fd;
struct stat sbuf;
if(mmapPtr==NULL) <--- why is this executed when I called MemoryMapFile() second time
{
// get file descriptor of file
if ((fd = open("example.c", O_RDONLY)) == -1)
{
perror("open");
exit(1);
}
if (stat("example.c", &sbuf) == -1)
{
perror("stat");
exit(1);
}
if ((data = mmap((caddr_t)0, sbuf.st_size, PROT_READ, MAP_SHARED, fd, 0)) == (caddr_t)(-1))
{
perror("mmap");
exit(1);
}
printf("mmap pointer %p \n",mmapPtr);
}
If char* mmapPtr is not a global or static pointer the line
never returns true as an uninitialized pointer has a random value, not a NULL value.
If you declare
it should work,( ignoring possible other errors)