Am I creating a memory leak and how to fix it
I am asking because I am creating an initialArray, but then I point it to a new array without freeing the initially allocated space. I tried to do free(initialArray)
before pointing it to my newArray, so I will free up the previously used array - it'll be like:
free(initialArray);
initialArray = newArray;
but I am getting a core dump. any help?
#include <stdio.h>
#include <stdlib.h>
#define ENLARGE_SIZE(x, y) x += y
#define SIZE_INCREMENT 10
int *get_set();
int main() {
int i = 0;
int *set = get_set();
printf("Array elements:\n");
while (*(set + i) != '\0') {
printf("%d,%d\n", *(set + i), i);
i++;
}
free(set);
return 1;
}
int *get_set() {
int *initialArray = malloc(sizeof(int) * SIZE_INCREMENT);
int arraySize = 5;
int arrayElementCount = 0;
int scannedInt;
int i = 0;
while (scanf("%d", &scannedInt) != EOF) {
printf("Scanned %d\n", scannedInt);
arrayElementCount++;
if (arraySize == arrayElementCount) {
int *newArray = realloc(initialArray, sizeof(int) * (ENLARGE_SIZE(arraySize, SIZE_INCREMENT)));
initialArray = newArray;
arraySize += SIZE_INCREMENT;
}
*(initialArray + i) = scannedInt;
i++;
}
return initialArray;
}
Comments
Post a Comment