c - linux c 使用的内存多于分配的内存

标签 c linux ipc shared-memory

我正在使用 POSIX 的共享内存..

我已经分配了 4KB,但我可以使用比 4KB 更多的空间...当我向内存中写入超过 10350 个字符时,它会出现段错误。等于 ~10350 字节/1024 = ~10KB ?

我相信操作系统应该保护内存以防止这种违规行为,但它允许我这样做?为什么 ?

生产者源代码,用于将某些内容放入共享内存段

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
int main(void)
{
const int size = 4096; //4kb
const char *name = "os";
const char *message = "Put more than 5000 chars it will work perfectly but less than 10350 or something like that";
int shm_fd;
void *ptr;
shm_fd = shm_open(name,O_CREAT | O_RDWR,0666);
ftruncate(shm_fd,size);// set the size to 4kb
ptr = mmap(0,size,PROT_WRITE | PROT_READ,MAP_SHARED,shm_fd,0);
sprintf(ptr,"%s",message);
ptr += strlen(message);
return 0;

最佳答案

我的系统也有 4KiB 页面大小,我的默认堆栈大小是 8KiB。 如果我这样做:

#define _BSD_SOURCE
#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 <unistd.h>
int main(){
  const int size = 4096;
  const char *name = "os";
  int shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);
  ftruncate(shm_fd,size);// set the size to 4kb
  char* ptr = (char*)mmap(0,size,PROT_WRITE | PROT_READ,MAP_SHARED,shm_fd,0);
  for(int i=0; i>=0; i++){
    printf("%d\n", i);
    ptr[i]='x';
  }
  return 0;
}

它会在 12KiB (12288) 处确定出现段错误。 我认为它在空间的开头mmaps,即紧邻堆栈(8KiB)并且溢出4KiB会导致堆栈空间被破坏,之后它段错误。

关于c - linux c 使用的内存多于分配的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33597517/

相关文章:

c - 如何用C语言学习编程

linux - 具有 shell 扩展的 Systemd 单元配置

linux - 在 64 位系统上向 Linux Kernel 3.13 添加新的系统调用

C++多进程共享内存实现

c - C中如何实现函数重载?

c++ - 用户空间和内核空间进程中的一组信号处理程序

c - 以 root 身份执行命令,无需 root 密码或 sudo

c++ - 不同线程中的 fsync() 和 write()

c++ - 我如何开始在类 Unix 操作系统(如 Linux)中编写守护进程?

apache - DBus 是我要找的吗?