【问题标题】:mmap and double pointermmap 和双指针
【发布时间】:2014-08-06 11:01:25
【问题描述】:

上下文:

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

下面的代码对我自己的智力挑战比其他任何事情都大。它可以帮助我处理指针等等。

我失败了。

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

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 函数?

前两个是 nil(正常),第三个是分配的,但最后两个是 nil。不好。

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

请问有什么“指针”吗?

谢谢

【问题讨论】:

  • *map = mmap(0, *size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);应该是这样的。
  • 以段错误结束

标签: c pointers mmap


【解决方案1】:

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多