I wanted to create a project where the requirement is to use shared memory to create a student report. Asks user for number of students report to be created and dynamically allocate the memory. But when I try to attach it, it gets into the error check if statement and after printing the error message it prints success.
JavaScript
x
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
typedef struct student
{
int id;
char name[20];
int maths;
int science;
int english;
}student;
int main()
{
student *ptr;
int n;
printf("enter the number of records you want to insert");
scanf("%d",&n);
ptr = (struct student*) malloc(n*sizeof(student));
int shmid;
key_t key = 9876;
shmid = shmget(key,(sizeof(ptr)*sizeof(student)), IPC_CREAT | 0666);
if(shmid < 0)
{
perror("shmget");
exit(1);
}
void* shm = shmat(shmid, NULL, 0);
if(shm = (void*) -1)
{
perror("Not attached");
exit(1);
}
return 0;
}
Advertisement
Answer
You need to think about what this line is doing:
JavaScript
if(shm = (void*) -1)
The right way to do it is:
JavaScript
if(shm == -1)