即时尝试实现一个基本程序,它将字符串数组写入共享内存然后从中读取它。我一直在分段故障。我真的不知道什么是错的(我真的搞砸了),因为我第一次使用共享内存。任何帮助将不胜感激,谢谢!分割错误:试图在共享内存中写入字符串数组c
代码:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
int shmid;
int i = 0;
key_t key = 123;
char (*array)[100][50];
shmid = shmget(key, 100 * 50, IPC_CREAT | 0666);
array = (char *)shmat(shmid, 0, 0);
// array = malloc(sizeof(int)*count);
for (i = 0; i < 10; i++)
{
strcpy(array[i], "arrayvalues");
}
for (i = 0; i < 10; i++)
{
printf("\n%s---\n", array[i]);
}
printf("\nWritting to memory succesful[+]\n");
shmid = shmget(key, 1024, IPC_CREAT | 0666);
array = (char *)shmat(shmid, 0, 0);
for (i = 0; i < 9; i++)
{
printf("\n%s---\n", array[i]);
}
printf("\nRead to memory succesful[+]\n");
shmdt((void *)array);
// shmctl(shmid, IPC_RMID, NULL);
return 0;
}
编辑:它不仅节省了在共享存储器数组[0]的值。
具有讽刺意味的是,您的名字是segfault。 –
@AjayBrahmakshatriya我在内存管理方面真的很糟糕! :) –
首先检查* shmget *和* shmat *返回错误值(详细信息请阅读手册页)。返回值是否正确? (一般来说,在缺少基本错误检查的代码上调试错误是没有意义的。) – hyde