gpt4 book ai didi

c - C语言中如何分配大内存

转载 作者:行者123 更新时间:2023-11-30 18:11:44 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,可以通过malloc(1024*1024*1024)从系统获取1GB内存.

得到内存的起始地址后,以我有限的理解,如果我想初始化它,只需使用 memset()实现。但事实是一段时间后会触发段错误

我尝试使用gdb查找原因,最终发现如果我对内存超过128 MB进行某些操作,就会导致此错误。

是否有任何规则限制程序只能访问小于 128 MB 的内存?或者我使用了错误的方式来分配和初始化它?

如果需要更多信息,请告诉我。

如有任何建议,我们将不胜感激。

[平台]

  • Linux 4.10.1 和 gcc 5.4.0
  • 使用 gcc test.c -o test 构建程序
  • CPU:英特尔 i7-6700
  • 内存:16GB

[代码]

    size_t mem_size = 1024 * 1024 * 1024;
...
void *based = malloc(mem_size); //mem_size = 1024^3
int stage = 65536;
int initialized = 0;
if (based) {
printf("Allocated %zu Bytes from %lx to %lx\n", mem_size, based, based + mem_size);
} else {
printf("Error in allocation.\n");
return 1;
}
int n = 0;
while (initialized < mem_size) { //initialize it in batches
printf("%6d %lx-%lx\n", n++, based+initialized, based+initialized+stage);
memset(based + initialized, '$', stage);
initialized += stage;
}

[结果]

  Allocated 1073741824 Bytes from 7f74c9e66010 to 7f76c9e66010
...
2045 7f7509ce6010-7f7509d66010
2046 7f7509d66010-7f7509de6010
2047 7f7509de6010-7f7509e66010
2048 7f7509e66010-7f7509ee6010 //2048*65536(B)=128(MB)
Segmentation fault (core dumped)

最佳答案

这里有两个可能的问题。首先是您没有正确使用malloc()。您需要检查它是否返回 NULL,或者非 NULL 值。

另一个问题可能是操作系统过度使用内存,并且内存不足 (OOM) killer 正在终止您的进程。 You can disable over-committing of memory and getting dumps to detect via these instructions.

编辑

两个主要问题:

  • 不要在日志记录语句内执行有副作用的操作(即:n++)。非常糟糕的做法,因为在大型项目中,日志记录调用通常在编译时被删除,现在程序的行为有所不同。
  • based 转换为 (char *)

这应该有助于解决您的问题。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
size_t mem_size = 1024 * 1024 * 1024;
printf("MEMSIZE: %lu\n", mem_size);
printf("SIZE OF: void*:%lu\n", sizeof(void*));
printf("SIZE OF: char*:%lu\n", sizeof(char*));
void *based = malloc(mem_size); //mem_size = 1024^3
int stage = 65536;
int initialized = 0;
if (based) {
printf("Allocated %zu Bytes from %p to %p\n", mem_size, based, based + mem_size);
} else {
printf("Error in allocation.\n");
return 1;
}
int n = 0;
while (initialized < mem_size) { //initialize it in batches
//printf("%6d %p-%p\n", n, based+initialized, based+initialized+stage);
n++;
memset((char *)based + initialized, '$', stage);
initialized += stage;
}

free(based);

return 0;
}

关于c - C语言中如何分配大内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44312720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com