gpt4 book ai didi

c - mmap 和双指针

转载 作者:行者123 更新时间:2023-11-30 17:30:23 25 4
gpt4 key购买 nike

上下文:

利用我的假期来摆弄一些指针:)

下面的代码对我自己来说是一次智力挑战。它可以帮助我处理指针等问题。

我失败了。

我承认,我没有强制执行错误管理的一致性。

Debian64。

问题:

我用 mmap 来解决问题,并且用双指针赋值来解决问题。这是代码:

#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;
}

问题:

如何才能检索到 write_to 函数的映射文件的正确地址?

前两个为零(正常),第三个已分配,但最后两个为零。不好。

我认为 mmap 调用中一切都出了问题,因为它给出了一个指针,但我有一个指向指针的指针。此后,地址不再相同。然后我就迷失了..

请问有什么“指针”吗?

谢谢

最佳答案

handle_a没有分配内存来存储指针

改变

char ** handle_a;

char * handle_a;

然后用作

second_function(path,&handle_a);

并像这样分配它;

*map = mmap(0, *size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

关于c - mmap 和双指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25158685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com