Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Expanding an array of ints using realloc crashes!
- #include <stdlib.h>
- #include <string.h>
- #include <stdio.h>
- int ExpandArrayOfInts(int* arrayToExpand, int expandBy, int inArraySize, int* outArraySize);
- int main (int argc, char** argv)
- {
- #if 1//CODE THAT WORKS
- int arraySize = 10;
- int* arrayDnmc = NULL;
- int* arrayDnmcExpndd;
- for (int i = 0; i< 10; ++i)
- {
- arrayDnmcExpndd = (int*)realloc(arrayDnmc, (arraySize + (i * 10)) * sizeof(int));
- if (arrayDnmcExpndd != NULL)
- {
- arrayDnmc = arrayDnmcExpndd;
- memset(arrayDnmc, 0, (arraySize + (i * 10)) * sizeof(int));
- }
- else
- {
- printf("Failed to (re)alloc memory for arrayDnmc!n");
- free(arrayDnmc);
- return -1;
- }
- }
- free(arrayDnmc);
- #else //CODE THAT DOESN'T WORK (Which I'm trying to make it work)
- int maxSize = 100;
- int arraySize = 10;
- int* arrayDnmc = NULL;
- arrayDnmc = (int*)malloc(arraySize * sizeof(int));
- if (arrayDnmc != NULL)
- {
- memset(arrayDnmc, 0, arraySize * sizeof(int));
- }
- else
- {
- printf("malloc failure!n");
- return -1;
- }
- while (arraySize < maxSize)
- {
- if (0 != ExpandArrayOfInts(arrayDnmc, 5, arraySize, &arraySize))
- {
- printf("Something went wrong.n");
- break;
- }
- //do something with the new array
- printf("new size: %in", arraySize);
- }
- free(arrayDnmc);
- #endif
- return 0;
- }
- int ExpandArrayOfInts(int* arrayToExpand, int expandBy, int inArraySize, int* outArraySize)
- {
- int newSize = inArraySize + expandBy;
- int* arrayTemp = (int*)realloc(arrayToExpand, newSize * sizeof(int));
- if (arrayTemp != NULL)
- {
- arrayToExpand = arrayTemp;
- *outArraySize = newSize;
- return 0;
- }
- return -1;
- }
- ntdll.dll!775c542c()
- [Frames below may be incorrect and/or missing, no symbols loaded for ntdll.dll]
- ntdll.dll!7758fdd0()
- ntdll.dll!7755b3fc()
- int ExpandArrayOfInts(int** arrayToExpand, int expandBy, int inArraySize, int* outArraySize)
- ExpandArrayOfInts(&arrayDnmc, 5, arraySize, &arraySize))
- int ExpandArrayOfInts(int** arrayToExpand, int expandBy, int inArraySize, int* outArraySize)
- .
- .
- .
- *arrayToExpand = (int*)realloc(*arrayToExpand, newSize * sizeof(int));
Advertisement
Add Comment
Please, Sign In to add comment