结构数组的奇怪行为

时间:2015-02-15 20:31:31

标签: c arrays struct

我有这个结构:

typedef struct {
    // ... other names
    size_t size; // size of frame
} frame_index_t;

typedef struct {
    // ... other names
    size_t         frames_read; // number of read frames
    size_t         frames_size; // size of frames array
    frame_index_t *frames;      // array of indexed frames
} state_t;

这是追加到数组:

// ... state allocated earlier
state->frames_size = 0;
state->frames_read = 0;
while (...) {
    if (state->frames_read == state->frames_size) {
        state->frames_size += FRAMES_CHUNK_SIZE; // += 100
        state->frames = realloc(
            state->frames,
            state->frames_size * sizeof(frame_index_t)
        );
        if (!state->frames) {
            goto error;
        }
    }
    state->frames[state->frames_read].size = calculated_frame_size;
    state->frames_read++;
}
state->frames_size = state->frames_read;
state->frames_read = 0;

后来我读了帧数组:

while (...) {
    printf(
        "Frame %lu of %lu\n",
        state->frames_read,
        state->frames_size
    );
    if (state->frames[state->frames_read].size == 0) {
        printf("Frame %lu is zero size\n", state->frames_read);
    } else if (state->frames[state->frames_read].size > 2000) {
        printf(
            "Frame %lu is %lu bytes",
            state->frames[state->frames_read].size
        );
    }
    state->frames_read += 1;
}

我有这个输出:

Frame 2684 of 11737
Frame 2685 of 11737
Frame 3344 is 0 bytes
Frame 2686 of 11737
Frame 2687 of 11737
Frame 2688 of 11737
Frame 2689 of 11737
Frame 2690 of 11737
Frame 2691 of 11737
Frame 2692 of 11737
Frame 4033 is 0 bytes
Frame 2693 of 11737
Frame 2694 of 11737

哇!怎么了?我误解了它。 可以影响其他资源分配吗?他们可以相交吗? Valgring没有说什么。没有内存泄漏,没有读取错误。

0 个答案:

没有答案