Trying to add an array of Integers to a POSIX Shared memory Object
Greetings all, I am really new to C and have been using it for about 1 month now at most. I am attempting to store an array from a function into a shared memory object, but I am unsure of how do so.
I know how to do it with Strings, but not really with an array of integers. The code is supposed to generate a collatz sequence of integers and add it to the shared memory object for another process/program to access it. Here is the code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int *calcCollatz(int n) {
int solution;
int *collatzSeq = malloc(sizeof(int));
int j = 0;
while (n != 1) {
if (n % 2 == 0) {
solution = n / 2;
n = solution;
collatzSeq[j] = n;
j++;
return collatzSeq;
} else {
solution = (3 * n) + 1;
n = solution;
collatzSeq[j] = n;
j++;
return collatzSeq;
}
}
}
int main(int argc, char *argv[])
{
const int SIZE = 4096; //size in bytes of Shared Memory Object
const char *sharedObj = "Shm"; //name of the Shared memory Object
int shm_fd; //Shared memory file descriptor
void *ptrShm; //Pointer to shared memory object
shm_fd = shm_open(sharedObj, O_CREAT | O_RDWR, 0666); //Create Shared Memory Object
ftruncate(shm_fd, SIZE); //configure the size of the shared memory object
ptrShm = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0); //Map the shared memory object in the space of the process
if (ptrShm == MAP_FAILED) {
printf("Map Failed\n");
return -1;
}
sprintf(ptrShm, argv[1]);
ptrShm += strlen(argv[1]);
sprintf(ptrShm, calcCollatz(atoi(argv[1])));
ptrShm += sizeof(calcCollatz(atoi(argv[1])));
printf("Writing the sequence to a shared memory object!\n");
return 0;
}
The int * collatz sequence method generates a sequence of integers per a collatz sequence until the value reaches 1. Please let me know if you need a clearer explanation.