0

I'm trying to allocate memory for 10x of my list struct then use it for my linked list but I keep getting a segmentation fault.

Valgrind

==3806== Invalid write of size 4
==3806==    at 0x4005FD: main (comp.c:14)
==3806==  Address 0xffffffffffffffff is not stack'd, malloc'd or (recently) free'd

Sample Code

#include <sys/mman.h>

typedef struct list {
    int num;
    struct list *next;
}list;

int main()
{
    list *nodes = mmap(NULL, sizeof(list) * 10, PROT_READ | PROT_WRITE, MAP_PRIVATE, -1, 0);

    nodes[0].num = 1;
    nodes[0].next = NULL;

}
Unknows player
  • 97
  • 1
  • 1
  • 5

1 Answers1

2

The 0xffffffffffffffff almost surely means that mmap failed. If you want to use it to allocate memory like malloc, you have to do error checking just as you would for malloc, except that you need to test the returned value against MAP_FAILED instead of NULL.

The failure is probably because you are trying to map a nonexistent file descriptor -1. This is only allowed when the MAP_ANONYMOUS flag is specified, which you did not include.

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82
  • MAP_ANONYMOUS is not recognized by clang. ` comp.c:19:101: error: use of undeclared identifier 'MAP_ANONYMOUS' struct list *nodes = mmap(NULL, sizeof(struct list) * 10, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); ` – Unknows player Aug 27 '20 at 04:53
  • Fixed it had to add #define _GNU_SOURCE at the top of the code. – Unknows player Aug 27 '20 at 05:02