I have a structure called House and it includes a char array for neighborhood. I am trying to read a database of houses and create an array for the houses with the same neighborhood. Reading part is working fine but while I'm creating a new array for a neighborhood my function only enters the loop for 23 times and finds first 23 houses with the same neighborhood and gives this error.
pro(4740,0x10d06f5c0) malloc: * error for object 0x7ff724d00030: pointer being realloc'd was not allocated pro(4740,0x10d06f5c0) malloc: * set a breakpoint in malloc_error_break to debug
typedef struct house{
int id;
int lotarea;
char street[5];
int saleprice;
char neighborhood[10];
int yearbuilt;
int overallqual;
int overallcond;
char kitchenqual[3];
} House;
House* get_neighborhoods(House house, House* array) {
printf("Get neighborhoods of house with id %d\n", house.id);
House* temp = array;
int counter = 1;
House* newarray = malloc(sizeof(House));
if (newarray == NULL) {
printf("Malloc error...");
}
while (temp != NULL) {
if (!strcmp(temp->neighborhood, house.neighborhood)) {
if (counter > 1) {
realloc(newarray, sizeof(House) * counter);
}
copy_house(newarray + counter - 1, temp);
print_house(newarray[counter - 1]);
counter++;
}
temp++;
}
return newarray;
}
You must assign the return value from realloc
. You have
realloc(newarray, sizeof(House) * counter);
The second time you call it (in the loop), the pointer you previously passed to it has already been free
d, but you discarded the new value.
newarray = realloc(newarray, sizeof(House) * counter);
Ideally you would assign the return value to a temporary variable, so you can check if the realloc
succeeded.