C程序问题“未释放指针被释放”

时间:2013-07-27 06:33:17

标签: c arrays pointers struct

我想我的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);
}

1 个答案:

答案 0 :(得分: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