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