【问题标题】:writing to shared memory core dump segmentation fault写入共享内存核心转储分段错误
【发布时间】:2016-05-11 08:29:24
【问题描述】:

我需要写入共享内存,所以我有

#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 个字符)然后读取它。

【问题讨论】:

  • read() 不为零终止 userInput。因此,您不能将strcat()userInput 一起使用。
  • 你应该使用 calloc() 而不是 malloc() 所以你的内存都是零字节开始的。无需添加 NUL 字节,只要您读取的内容最多比分配的大小少 1。并阅读您的 C 书籍以了解 string 是什么以及哪些函数接受/返回字符串,以及哪些函数接受/返回任意字符数组。
  • char* userInput = malloc(5); 更改为 char* userInput = calloc(5, sizeof(char)); 您的 UserInput "C-String" 不是使用 malloc 终止的 null 并且仅读取 3 个字节。

标签: c malloc shared-memory coredump backslash


【解决方案1】:

这个:

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

不是有效的 C,它不会“抛出异常”,因为 C 没有异常。也许它会崩溃,但无论如何这应该是可以预料的,因为你甚至没有编写有效的代码。使用可以拒绝此类明显无效代码的编译器。


编辑:和这个:

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

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

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);

即直接读取到目的地,而不是临时缓冲区。

【讨论】:

  • userInput 也不是以零结尾的。
  • 我已经编译并检查了所有内容..我只是不知道如何简单地将“b34”写入共享内存,以便我以后能够读取它..这就是我的全部问题
  • @ZoharArgov:你不可能编译了strcat(userInput, '\0'); 并“检查了所有内容”。这是无法使用的无效代码。你的编译器甚至不应该编译它。
  • @ZoharArgov:当您的编译器向您发出警告时,您需要在运行程序之前停止并修复它。否则你会浪费很多时间,无论是你的还是我们的。
  • @ZoharArgov:我在回答中添加了更多内容。希望这会有所帮助。
【解决方案2】:

函数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);
}

【讨论】:

    猜你喜欢
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    • 2015-06-25
    • 2021-06-03
    相关资源
    最近更新 更多