6_fingered_man
6_fingered_man

Reputation: 21

mmap Cannot allocate memory -- definitely not out of memory

For whatever reason I can't open any size of file using mmap in C. I am probably missing something obvious, so your suggestions would be greatly appreciated. I searched similar responses and didn't find anything that helped. Here is my code -- yes, it is very simple.

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc, const char * argv[])
{
void * data;
int fd;
struct stat sb;
fd = open("small.txt", O_RDONLY);

data = mmap(0, sb.st_size, PROT_READ, MAP_SHARED, fd, 0);
if (data == MAP_FAILED) perror("mmap");

return 0;
}

small.txt is a very small text file, it is 4.0 K in size. The particular machine this is being run on has a lot of RAM (> 500G). Memory is not the problem here. I realize it is something I am doing, and I would be very grateful if you could point it out for me.

The error I am getting is "mmap: Cannot allocate memory"

Upvotes: 1

Views: 1441

Answers (1)

BlackMamba
BlackMamba

Reputation: 10252

Maybe you can use this code, please see this link:http://man7.org/linux/man-pages/man2/mmap.2.html

int fd;
struct stat sb;
fd = open("small.txt", O_RDONLY);

if (fstat(fd, &sb) == -1)           /* To obtain file size */
    handle_error("fstat");

Upvotes: 1

Related Questions