I'm using Visual Studio 2017 and I have this code in C. When I run in VS it fails, but when I compile with gcc it runs perfectly. The error is this:
Exception thrown at 0x779BE643 (ntdll.dll) in GestaoFinanceira.exe: 0xC0000005: Access violation reading location 0x00000009.
This is my code.
I'm using this struct type:
struct budget {
struct tm time;
float valor;
};
struct geral {
struct budget *b;
int nelem_budget;
};
In main I call a function that will read from a file and save the values is the struct g->b[]
as the number of elements in g->nelem_budget
int main() {
struct geral *g = (struct geral *)malloc(sizeof(struct geral));
readFileBudget(g);
// just to check if the read was ok
showBudget(g->b, g->nelem_budget);
addBudget(g);
// to check again if the item added is ok
showBudget(g->b, g->nelem_budget);
system("Pause");
return 0;
}
Here is when the error appens:
void addBudget(struct geral *g) {
int month, year;
float value;
// in the future, this values are to be an user input
month = 5;
year = 2015;
value = 5000;
printf("Month: %d, Year: %d, Value: %f\n", month, year, value);
g->b[g->nelem_budget].time.tm_mon = month;
g->b[g->nelem_budget].time.tm_year = year;
g->b[g->nelem_budget].valor = value;
g->nelem_budget++;
struct budget *tmp = NULL;
tmp = g->b;
g->b = realloc(g->b, g->nelem_budget * sizeof(struct budget));
if (g->b == NULL) { //reallocated pointer ptr1
free(tmp);
printf("error-addBudget->realloc");
exit(EXIT_FAILURE);
}
// just for debug
printf("month: %d, year: %d, value: %f\n", g->b[g->nelem_budget - 1].time.tm_mon, g->b[g->nelem_budget - 1].time.tm_year, g->b[g->nelem_budget - 1].valor);
}
I have an empty value at the end of the g->b
array, that's why I first add the values, and then I call the realloc
.