写入共享内存核心转储分段故障

时间:2016-05-11 08:29:24

标签: c malloc shared-memory coredump backslash

我需要写共享内存,因此我有

#define FLAGS IPC_CREAT | 0644
int main() {
key = ftok("ex31.c", 'k');
shmid = shmget(key, 3, FLAGS);
shmaddr = shmat(shmid,0,0);    // THOSE LINES WORK AS EXPECTED

char* userInput = malloc(5);
read(0, userInput, 3);  // I want to read "b34" for example, WORKS GOOD
strcpy(shmaddr,userInput);   // THROWS EXCEPTION!
}

它会在strcat中抛出异常,如果我删除它,则会在strcpy的下一行抛出异常。 我需要写入内存“b34\0”(4个字符),然后阅读它。

2 个答案:

答案 0 :(得分:6)

此:

strcat(userInput, '\0');   //THROWS EXCEPTION!!

不是有效的C,它不会引发异常"因为C没有例外。也许它会崩溃,但无论如何都应该预料到,因为你甚至没有编写有效的代码。使用拒绝明显无效代码的编译器。

编辑:和:

char* userInput = malloc(5);
read(0, userInput, 3);
strcpy(shmaddr,userInput);

无效是因为您读取了三个字符,而userInput中的最后两个字符未初始化,然后您调用strcpy()userInput读取空终止字符串,但您没有null -terminated字符串,所以它是未定义的行为,任何事情都可能发生 - 包括崩溃。所以试试这个:

const size_t INPUT_MAX_SIZE = 3;
char userInput[INPUT_MAX_SIZE + 1];
read(STDIN_FILENO, userInput, INPUT_MAX_SIZE);
userInput[INPUT_MAX_SIZE] = '\0'; // add null terminator
strcpy(shmaddr,userInput);

或者更好:

read(STDIN_FILENO, shmaddr, INPUT_MAX_SIZE);

也就是说,只需直接读取到目的地,而不是临时缓冲区。

答案 1 :(得分:1)

函数strcatstrcpy都希望参数为以空字符结尾的字符串,在这种情况下,userInputshmaddr都不满足这个条件,这就是为什么你看程序崩溃了。试试这个:

#define FLAGS IPC_CREAT | 0644
int main(void) {
    key = ftok("ex31.c", 'k');
    shmid = shmget(key, 4, FLAGS);  // the buffer needs at least size 4 to hold the 3 char string and the null terminator
    shmaddr = shmat(shmid, 0, 0);

    char* userInput = malloc(5);
    read(0, userInput, 3);
    userInput[3] = '\0';
    strcpy(shmaddr, userInput);
}
相关问题