The goal of this code is to create a shared memory space and write n's value to it in the child then print all the numbers generated in from the parent process. But this presently just prints out memory addresses like 16481443B4 which change every time I run the program. I am not sure if I am writing to the shared memory incorrectly or reading from the shared memory incorrectly. Possibly both.
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/shm.h>
#include <sys/mman.h>
int main(int argc, char** argv){
//shared memory file descriptor
int shm_fd;
//pointer to shared memory obj
void *ptr;
//name of shared obj space
const char* name = "COLLATZ";
//size of the space
const int SIZE = 4096;
//create a shared memory obj
shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);
//config size
ftruncate(shm_fd, SIZE);
//memory map the shared memory obj
ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);
int n = atoi(argv[1]);
pid_t id = fork();
if(id == 0) {
while(n>1) {
sprintf(ptr, "%d",n);
ptr += sizeof(n);
if (n % 2 == 0) {
n = n/2;
} else {
n = 3 * n + 1;
}
}
sprintf(ptr,"%d",n);
ptr += sizeof(n);
} else {
wait(NULL);
printf("%d\n",(int*)ptr);
}
//Umap the obj
munmap(ptr, SIZE);
//close shared memory space
close(shm_fd);
return 0;
}