我正在尝试初始化我的struct中的一些变量,但是当我将前变量赋值为零时,我遇到了一个seg错误。特别是newBuff-> front = 0;
typedef struct buffer{
pthread_mutex_t lock;
pthread_cond_t shout;
int front;
int rear;
char bytes[1024];
} buffer;
int main(int argc, char const *argv[]) {
FILE *file = fopen(argv[1], "r");
if (argc != 2){
printf("You must enter in a file name\n");
}
printf("%lu\n", sizeof(file));
int shmid;
char path[] = "~";
key_t key = ftok(path, 7);
shmid = shmget(key, SIZE, 0666 | IPC_CREAT | IPC_EXCL); //shared memory creation
buffer* newBuff = (buffer*) shmat(shmid, 0, 0);
newBuff->front = 0;
答案 0 :(得分:0)
您未检查newBuff
返回的shmat()
的值,以确保其无效,例如: (void*) -1
(按http://man7.org/linux/man-pages/man2/shmop.2.html)。您还需要检查shmget()
的返回值,以确保它在第一时间成功。
几乎可以肯定,newBuff
为-1,尝试取消引用会给你一个段错误。
答案 1 :(得分:0)
我能看到的几件事:
上面说的,我看不到你的整个代码,但这是我的建议:
typedef struct buffer{
pthread_mutex_t lock;
pthread_cond_t shout;
int front;
int rear;
char bytes[1024];
} buffer;
int main(int argc, char const *argv[]) {
int shmid = -1;
FILE *file = NULL;
if (argc != 2){
printf("You must enter in a file dumbass\n");
// And you must terminate here your program!
return 1;
}
file = fopen(argv[1], "r");
// Another check that you are not making and can raise a SIGVSEG
if (file == NULL) {
printf("The file '%s' can not be opened\n", argv[1]);
return 1;
}
printf("File size: %lu\n", sizeof(file));
char path[] = "~";
key_t key = ftok(path, 7);
// Another check
if (key == -1) {
fclose(f);
printf("The path '%s' does not exist or cannot be accessed\n", path);
return 1;
}
shmid = shmget(key, SIZE, 0666 | IPC_CREAT | IPC_EXCL);
// One more check
if (shmid == -1) {
fclose(f);
printf("An error happened getting shared memory identifier\n");
return 1;
}
buffer* newBuff = (buffer*)shmat(shmid, 0, 0);
// And finally! Another potential source that could raise a SIGVSEG
if (buffer == NULL) {
fclose(f);
printf("An error happened getting the shared memory area\n");
return 1;
}
newBuff->front = 0;
请!检查每次返回的功能!你无法想象会发生多少真正的问题,因为不良的做法不能正确检查这些回报。