gpt4 book ai didi

c - 尝试使用 for 循环初始化 1G 内存时访问内存崩溃

转载 作者:太空宇宙 更新时间:2023-11-04 06:31:32 25 4
gpt4 key购买 nike

我想知道为什么下面的代码会崩溃?

我的环境是ubuntu64,gcc 4.8.1

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define SIZE 1024*1024*1024
int main()
{
printf("%ld,%ld,%ld\n",sizeof(int),sizeof(long),sizeof(size_t));//output 4,8,8
printf("%ld\n",SIZE); //output 1073741824

int *p = (int*)malloc(SIZE);
if(!p){
perror("malloc");
exit(1);
}

memset(p,0,SIZE); //this works fine

size_t i=0;
for(;i<SIZE;++i){
p[i] = 10; //gdb shows when crashed i = 268436476
}
}

最佳答案

您正在分配 SIZE bytes,而不是 SIZE ints。因此,当您尝试在 for 循环中写入 SIZE 整数时,您将超出已分配内存的范围进行写入。

改变:

int *p = (int*)malloc(SIZE);

到:

int *p = malloc(SIZE * sizeof(p[0]));

另请注意,我删除的 int 转换为 redundant and potentially harmful .

关于c - 尝试使用 for 循环初始化 1G 内存时访问内存崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19989232/

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