【发布时间】: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