Reputation: 23
I guess my C is a little bit rusty now because I can't quite figure out the issue here. I'm pretty sure it lies within parse_historical_data(). If I comment it out and just run allocate_historical_data() and free_historical_data() then the program runs just fine, but when I uncomment it and run the whole thing I get an error that says "pointer being freed was not allocated".
struct historical_data {
char **timestamp;
float *close;
float *high;
float *low;
float *open;
int *volume;
int count;
};
struct historical_data *h = (struct historical_data *) malloc(
sizeof(struct historical_data));
void allocate_historical_data(struct historical_data *h,
int days, int interval)
{
int i;
h->close = malloc(days * (60/interval) * 400 * sizeof(float));
h->high = malloc(days * (60/interval) * 400 * sizeof(float));
h->low = malloc(days * (60/interval) * 400 * sizeof(float));
h->open = malloc(days * (60/interval) * 400 * sizeof(float));
h->timestamp = (char **) malloc(days * (60/interval)
* 400 * sizeof(char *));
for (i = 0; i < days * (60/interval) * 400; i++)
h->timestamp[i] = malloc(25 * sizeof(char));
h->volume = malloc(days * (60/interval) * 400 * sizeof(int));
}
void parse_historical_data(struct historical_data *h, char *raw_data)
{
char *csv_value;
int i = 0;
csv_value = strtok(raw_data, ",");
h->timestamp[i] = csv_value;
while (csv_value != NULL) {
csv_value = strtok(NULL, ",");
h->open[i] = atof(csv_value);
csv_value = strtok(NULL, ",");
h->high[i] = atof(csv_value);
csv_value = strtok(NULL, ",");
h->low[i] = atof(csv_value);
csv_value = strtok(NULL, ",");
h->close[i] = atof(csv_value);
csv_value = strtok(NULL, "\n");
h->volume[i] = atoi(csv_value);
if (h->volume[i] == 0) // Junk data.
i--;
i++;
csv_value = strtok(NULL, ",");
h->timestamp[i] = csv_value;
}
h->count = i;
}
void free_historical_data(struct historical_data *h, int days, int interval)
{
int i;
free(h->close);
free(h->high);
free(h->low);
free(h->open);
for (i = 0; i < days * (60/interval) * 400; i++)
free(h->timestamp[i]);
free(h->timestamp);
free(h->volume);
free(h);
}
Upvotes: 1
Views: 415
Reputation: 53316
I think the problem lies with h->timestamp
.
In parse_historical_data()
you do
csv_value = strtok(raw_data, ",");
h->timestamp[i] = csv_value;
...
...
csv_value = strtok(NULL, ",");
h->timestamp[i] = csv_value;
h->timestamp[i]
is not assigned with allocated string/pointer. Rather it just points to same string - char *
but from different index.
You may want to change it too
strcpy(h->timestamp[i], csv_value); //as you have already allocated for it
Upvotes: 1