I am trying to attach an array of strings to the shared memory in C. I have tried my best to attach the array of strings ( array1 and array 2 to the shared memory).
Here, array1 and array2 are arrays of strings of width 20 characters and size 5 ( How do I specify that in the attachment is also not very clear to me).
Also, a and b are 1-D integer and float arrays respectively, of size 5.
I want to change the state of the array of strings by updating their value at runtime, as I am doing.
#include <stdio.h>
#include <stdlib.h>
#include<sys/shm.h>
#define NUMBER_OF_DATA 5
int main()
{
int size=(NUMBER_OF_DATA*(sizeof(int)+sizeof(float))) + (2*(20*NUMBER_OF_DATA));
key_t key;
key=ftok("/home/android/Desktop/newww.c",4);
int shmid=shmget(key,size,0777|IPC_CREAT);
int *a=(int *)shmat(shmid,0,0);
float *b=(float *)(a+NUMBER_OF_DATA);
char **array1=(char **)(b+NUMBER_OF_DATA);
char **array2=(char **)(array1+(20*NUMBER_OF_DATA));
int i;
for(i=0;i<5;i++)
{
printf("enter value\n");
scanf("%s",array1[i]);
}
shmdt(&shmid);
shmctl(shmid,IPC_RMID,0);
return 0;
}
My other process does the following
int shmid=shmget(key,size,0777|IPC_CREAT);
int *a1=(int *)shmat(shmid,0,0);
float *b1=(float *)(a1+NUMBER_OF_DATA);
char **array11=(char **)(b1+NUMBER_OF_DATA);
char **array22=(char **)((char *)array11+(20*NUMBER_OF_DATA));
for(i=0;i<NUMBER_OF_DATA;i++)
{
a1[i]=aaa[i];
b1[i]=bbb[i];
array11[i]=array111[i];
array22[i]=array2222[i];
}
where aaa,bbb,array111 and array222 are other arrays from which the values are loaded into the shared memory by this process.
These 2 processes are together not helping me achieve what i wanted.
It would be great if someone could point out the reason and tell me the correct way to attach the array of strings to memory. Thanks.
Let’s use a debugger to find where the error is happening. First compile with debugging turned on, then run it:
The
btcommand, short for backtrace, will show where the error occurred:Here it’s line 20, calling
scanf(). Let’s moveupthe stack to get into the right frame:And now the
pcommand, short for print, to examine values.Aha! The line
scanf("%s", array1[i])is trying to store a string to the value ofarray1[i]—0—rather than to its address.Let’s fix that by changing the line to:
Now, recompile, and it works:
However, there’s now a compiler warning on my machine:
But that’s another question for you to figure out 🙂