You only malloc enough space for one int in collatzSeq.
And think about how you are using sprintf in main. The last one receives an int* pointing to an int array and passes that as the 2nd parameter of sprintf. The second parameter of sprintf should be a string.
And sizeof a pointer is just the size of the pointer, not the size of the array it points to.
To copy the data you should use memcpy.
To determine its size, you should have calcCollatz return j through a int* parameter.
Code:
// gcc -Wall -o shmcollatz shmcollatz.c -lrt
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#define MAX_SEQ_SIZE 1000
void error_exit(const char *msg) {
if (errno)
perror(msg);
else
fprintf(stderr, "%s\n", msg);
exit(EXIT_FAILURE);
}
int *calcCollatz(int n, int *size) {
int *collatzSeq = malloc(MAX_SEQ_SIZE * sizeof *collatzSeq);
int j = 0;
while (n != 1) {
if (n % 2 == 0)
n /= 2;
else
n = (3 * n) + 1;
if (j == MAX_SEQ_SIZE)
error_exit("MAX_SEQ_SIZE reached");
collatzSeq[j++] = n;
}
*size = 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
if (argc != 2) error_exit("Usage: shmcollatz N\n");
int shm_fd = shm_open(sharedObj, O_CREAT | O_RDWR, 0666);
ftruncate(shm_fd, SIZE); //configure the size of the shm
char *ptrShm = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (ptrShm == MAP_FAILED) error_exit("map failed");
char *pshm = ptrShm;
pshm += sprintf(pshm, "%s", argv[1]);
int size = 0;
int *a = calcCollatz(atoi(argv[1]), &size);
memcpy(pshm, a, size * sizeof *a);
pshm += size * sizeof *a;
// ... etc
return 0;
}