gpt4 book ai didi

c - 分配仅在释放时失败

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

在调试程序时,程序会按预期运行。运行发行版时,它告诉我空间不足。为什么会发生这种情况,如何让它在发布 exe 中运行?

我找到了一些其他文章,但我不明白相似之处在哪里。 C malloc weird behavior on debug/release

#include <stdio.h> 
#include <stdlib.h>
#include <time.h>

#define AMOUNT 100000 // amount of random numbers
#define RANDOM (rand() & 0x1F) + (rand() << 16) // 32 bit random number

struct sNumStruct {
unsigned int uiNum; // number
struct sNumStruct *pNext; // next
struct sNumStruct *pPrev; // previous
};

int main()
{
/// initializing
srand(time(NULL)); // rand() initializer
unsigned int i = 0; // counter
struct sNumStruct * pNumbers; // pointer to number structure
struct sNumStruct * pStart; // pointer to start of list
struct sNumStruct * pLast; // pointer to end of list

/// random number generation
printf("Generating %d random numbers ...\n", AMOUNT);

pStart = (struct sNumStruct*)malloc(sizeof(struct sNumStruct*)); // allocating memory for first element
if(pStart == NULL) // allocation failed?
{
perror("-1"); // print error -1
return -1;
}
pStart->pNext = NULL; // next element is NULL
pStart->pPrev = NULL; // prev element is NULL

pNumbers = pStart; // point to number structure
pNumbers->uiNum = RANDOM; // get random number

for(i = 0; i < AMOUNT; i++) // repeat AMOUNT times
{
printf("%d,", i); // <---------- DEBUG
pNumbers->pNext = (struct sNumStruct*)malloc(sizeof(struct sNumStruct*)); // allocating memory for next element
if(pNumbers->pNext == NULL) // allocation failed?
{
perror("-2"); // print error -2
return -2;
}
(pNumbers->pNext)->pPrev = pNumbers; // current element is previous from next
pNumbers = pNumbers->pNext; // next element
pNumbers->uiNum = RANDOM; // random number
pNumbers->pNext = NULL; // next element is NULL
}
pLast = pNumbers;

printf("\n... done generating numbers\n");

// sort(&pNumbers);

return 0;
}

我得到的输出是:“生成 100000 个随机数......0,1,-2: 空间不足

进程返回 -2 (0xFFFFFFFE)”

“0,1”是它分配了多少个元素。所以它在第一个“下一个元素”分配时失败。“-2”证实了上面的说法

希望看到:“生成 100000 个随机数......0,1, ....(不会输入所有数字)... 99998,99999,... ...完成生成数字

进程返回 0"

最佳答案

当你这样做时:

pStart = (struct sNumStruct*)malloc(sizeof(struct sNumStruct*));

你正在分配一个指针的大小,如果你在 64 位系统上,它可能是 8 个字节。你应该使用 :

pStart = (struct sNumStruct*)malloc(sizeof(struct sNumStruct));(没有指针)

这将为您的结构分配所需的大小。

也许这会有所帮助?

关于c - 分配仅在释放时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57495662/

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