Reputation: 1765
Taking advantage of my holidays to fiddle with some pointers :)
The code below is an intellectual challenge to myself more than anything else. it helps me working on pointers and so on.
And I fail.
I didn't enforce the coherence with error management, I confess.
Debian64.
I make my way with mmap and I litteraly plundge with a double pointer assignation. here is the code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
static int mmap_create(const char ** restrict map, const char * restrict path, const unsigned int * restrict size)
{
int fd;
int result;
fd = open(path, O_RDWR | O_CREAT,(mode_t)0777);
if (fd == -1)
{
printf("fail3\n");
close(fd);
return -1;
}
result = lseek(fd, *size-1, SEEK_SET);
if (result == -1)
{
printf("fail4\n");
close(fd);
return -1;
}
result = write(fd, "", 1);
if (result != 1)
{
printf("fail0\n");
close(fd);
return -1;
}
/* Here is my problem since map is a pointer to pointer */
map = mmap(0, *size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (map == MAP_FAILED)
{
printf("fail\n");
close(fd);
return -1;
}
printf("pointing to %p\n",map);
return 0;
}
static void second_function(const char * restrict path, const char ** restrict handle)
{
printf("pointing to %p\n",handle);
/* CREATE MMAP */
unsigned int value = 100;
mmap_create(handle,path,&value);
}
static void write_to(char ** map)
{
printf("pointing to %p\n",map);
}
int main(int argc, char * argv[])
{
const char path[] = "/my/path/";
char ** handle_a;
printf("pointing to %p\n",handle_a);
second_function(path,handle_a);
printf("pointing to %p\n",handle_a);
write_to(handle_a);
/*munmap*/
return 0;
}
How could I do to be able to retrieve the right address of the mapped file up to the write_to function ?
The first two are nil (normal) the third is assigned but the last two ones are nil. Not good.
I think it all goes wrong in the mmap call since it gives a pointer but I have a pointer to pointer. Thereafter, the addresses are not the same anymore. And then, I am lost..
Any "pointer" please?
Thanks
Upvotes: 0
Views: 1767
Reputation: 14708
handle_a has no memory allocated to store the pointer
change
char ** handle_a;
to
char * handle_a;
and then use as
second_function(path,&handle_a);
and assign it like;
*map = mmap(0, *size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
Upvotes: 1