Some starters:
creating a dynamic array of a data structure called fractions. Fractions has functions for setting, printing, intiting etc.
I kept getting an error for double freeing or corruption, along with a lot of gibberish from the memory map. This is the error from the output:
double free or corruption (top): 0x0000000001976010 *
I get that it is being freed/deleted twice but here is the code that generates the error:
#include <stdio.h>
#include <stdlib.h>
#include "fraction.h"
main() {
long long int size = 0;
long long int capacity = 10;
int FSize = sizeof(struct fraction);
struct fraction* array = NULL;
struct fraction in;
array = (struct fraction*)malloc(FSize * capacity);
if (array == NULL) {
printf("MALLOC DID NOT WORK\n");
exit(1);
}
int i = 0;
for (i = 0; i < 17; i++) {
if (size == capacity) {
capacity = capacity * 2;
struct fraction* temp = NULL;
temp = (struct fraction*)realloc(array, FSize * capacity);
// free(array);
array = temp;
free(temp);
}
SetFrac(&in);
array[size++] = in;
}
printf("IT MADE IT HERE >>>>>>>>>>>>>>>>>> \n");
getchar();
for (i = 0; i < size; i++) {
struct fraction t = array[i];
PrintFrac(&t);
}
free(array);
return 0;
}
Here is the code that works
#include <stdio.h>
#include <stdlib.h>
#include "fraction.h"
main() {
long long int size = 0;
long long int capacity = 10;
int FSize = sizeof(struct fraction);
struct fraction* array = NULL;
struct fraction in;
array = (struct fraction*)malloc(FSize * capacity);
if (array == NULL) {
printf("MALLOC DID NOT WORK\n");
exit(1);
}
int i = 0;
for (i = 0; i < 17; i++) {
if (size == capacity) {
capacity = capacity * 2;
struct fraction* temp = NULL;
temp = (struct fraction*)realloc(array, FSize * capacity);
// free(array);
array = temp;
free(temp);
}
SetFrac(&in);
array[size++] = in;
}
printf("IT MADE IT HERE >>>>>>>>>>>>>>>>>> \n");
getchar();
for (i = 0; i < size; i++) {
struct fraction t = array[i];
PrintFrac(&t);
}
// free(array);
return 0;
}
Am I using the free() function wrong?