When debugging the program works how it's supposed to. When running the release version, it tells me I have not enough space. Why is this happening and how can I make it run in the release exe?
I found some other article, but I don't get where the similarities are. 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;
}
The output I'm getting is: "Generating 100000 random numbers ... 0,1,-2: Not enough space
Process returned -2 (0xFFFFFFFE)"
the "0,1," are how many elements it has allocated. so it fails on the first "next element" allocation. "-2" confirms the statement above
expected to see: "Generating 100000 random numbers ... 0,1, ....(not gonna type all numbers)... 99998,99999, ... ... done generating numbers
Process returned 0"
When you do this :
pStart = (struct sNumStruct*)malloc(sizeof(struct sNumStruct*));
You are allocating the sizeof a pointer, which is probably 8bytes if you are on a 64bits system. You should rather use :
pStart = (struct sNumStruct*)malloc(sizeof(struct sNumStruct));
(without the pointer)
which will allocate the size needed for your struct.
Maybe this might help ?
User contributions licensed under CC BY-SA 3.0