1

我想我的 C 现在有点生锈了,因为我无法完全弄清楚这里的问题。我很确定它位于 parse_historical_data() 中。如果我将其注释掉并只运行 allocate_historical_data() 和 free_historical_data() 那么程序运行得很好,但是当我取消注释并运行整个程序时,我收到一个错误,提示“未分配指针被释放”。

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);
}
4

1 回答 1

1

我认为问题出在h->timestamp.

parse_historical_data()你做

csv_value = strtok(raw_data, ",");
h->timestamp[i] = csv_value;
...
...
    csv_value = strtok(NULL, ",");
    h->timestamp[i] = csv_value;

h->timestamp[i]没有分配分配的字符串/指针。相反,它只是指向相同的字符串 -char *但来自不同的索引。

你可能也想改变它

strcpy(h->timestamp[i], csv_value); //as you have already allocated for it
于 2013-07-27T06:41:19.737 回答