scanf上的分段错误?

时间:2018-10-10 21:56:29

标签: scanf

我不明白为什么scanf调用会导致分段错误。试图制作一个只有int编号和scanf的单独文件,但没有问题。真的很困惑,这里需要帮助。我在scanf参数中使用了指针,因此我怀疑该错误可能是由于scanf与共享内存之间的交互造成的?

#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <semaphore.h>

int main() {
const char *name = "message";
const char *names = "sem";
const int SIZE = 4096;
const int size = 1;
int number;

int shm_fd1;
int shm_fd2;
char *ptr; // Pointer to shared memory
sem_t *sem;

/* create the shared memory segment */
shm_fd1 = shm_open(name, O_CREAT | O_RDWR, 0666);
shm_fd2 = shm_open(names, O_CREAT | O_RDWR, 0666);

/* configure the size of the shared memory segment */
ftruncate(shm_fd1, SIZE);
ftruncate(shm_fd2, size);

/* initialize semaphore */
if (sem_init(sem, 1, 1) < 0) { // 1 = multiprocess
    fprintf(stderr, "ERROR: could not initialize semaphore.\n");
    exit(0);
}

/* now map the shared memory segment in the address space of the process */
ptr = mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd1, 0);
sem = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd2, 0);
if (ptr == MAP_FAILED) {
    printf("Map failed\n");
    return -1;
}
if (sem == MAP_FAILED) {
    printf("Map failed\n");
    return -1;
}
strcpy(ptr, "Hello from the server\n");

/* store and read from the shared memory region */
printf("Message: %s\n", ptr);
printf("0. Quit\n 1. Change message\n 2. Check message\n");
printf("Type an integer: ");
scanf("%d", &number); //confirmed this causes the error

如果我删除程序上方的行,则不会出现问题。除此文件外,单独的零件也可以正常工作。

if (number == 1) {
    sem_wait(sem);
    printf("Enter your message: ");
    scanf("%s", ptr);
    sem_post(sem);
}
else if (number == 2) {
    printf("Message: %s\n", ptr);
}
else {
    /*break;*/
}

/* remove the shared memory segment */
if (shm_unlink(name) == -1) {
    printf("Error removing %s\n",name);
    exit(-1);
}

return 0;
}

0 个答案:

没有答案
相关问题