Guest User

Untitled

a guest
Jun 26th, 2012
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. Expanding an array of ints using realloc crashes!
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <stdio.h>
  5.  
  6. int ExpandArrayOfInts(int* arrayToExpand, int expandBy, int inArraySize, int* outArraySize);
  7.  
  8.  
  9. int main (int argc, char** argv)
  10. {
  11. #if 1//CODE THAT WORKS
  12.  
  13. int arraySize = 10;
  14. int* arrayDnmc = NULL;
  15. int* arrayDnmcExpndd;
  16.  
  17.  
  18. for (int i = 0; i< 10; ++i)
  19. {
  20. arrayDnmcExpndd = (int*)realloc(arrayDnmc, (arraySize + (i * 10)) * sizeof(int));
  21. if (arrayDnmcExpndd != NULL)
  22. {
  23. arrayDnmc = arrayDnmcExpndd;
  24. memset(arrayDnmc, 0, (arraySize + (i * 10)) * sizeof(int));
  25. }
  26. else
  27. {
  28. printf("Failed to (re)alloc memory for arrayDnmc!n");
  29. free(arrayDnmc);
  30. return -1;
  31. }
  32. }
  33. free(arrayDnmc);
  34.  
  35. #else //CODE THAT DOESN'T WORK (Which I'm trying to make it work)
  36.  
  37. int maxSize = 100;
  38. int arraySize = 10;
  39. int* arrayDnmc = NULL;
  40.  
  41. arrayDnmc = (int*)malloc(arraySize * sizeof(int));
  42. if (arrayDnmc != NULL)
  43. {
  44. memset(arrayDnmc, 0, arraySize * sizeof(int));
  45. }
  46. else
  47. {
  48. printf("malloc failure!n");
  49. return -1;
  50. }
  51.  
  52. while (arraySize < maxSize)
  53. {
  54. if (0 != ExpandArrayOfInts(arrayDnmc, 5, arraySize, &arraySize))
  55. {
  56. printf("Something went wrong.n");
  57. break;
  58. }
  59. //do something with the new array
  60. printf("new size: %in", arraySize);
  61. }
  62. free(arrayDnmc);
  63. #endif
  64. return 0;
  65. }
  66.  
  67. int ExpandArrayOfInts(int* arrayToExpand, int expandBy, int inArraySize, int* outArraySize)
  68. {
  69. int newSize = inArraySize + expandBy;
  70. int* arrayTemp = (int*)realloc(arrayToExpand, newSize * sizeof(int));
  71. if (arrayTemp != NULL)
  72. {
  73. arrayToExpand = arrayTemp;
  74. *outArraySize = newSize;
  75. return 0;
  76. }
  77. return -1;
  78. }
  79.  
  80. ntdll.dll!775c542c()
  81. [Frames below may be incorrect and/or missing, no symbols loaded for ntdll.dll]
  82. ntdll.dll!7758fdd0()
  83. ntdll.dll!7755b3fc()
  84.  
  85. int ExpandArrayOfInts(int** arrayToExpand, int expandBy, int inArraySize, int* outArraySize)
  86.  
  87. ExpandArrayOfInts(&arrayDnmc, 5, arraySize, &arraySize))
  88.  
  89. int ExpandArrayOfInts(int** arrayToExpand, int expandBy, int inArraySize, int* outArraySize)
  90. .
  91. .
  92. .
  93. *arrayToExpand = (int*)realloc(*arrayToExpand, newSize * sizeof(int));
Advertisement
Add Comment
Please, Sign In to add comment