简体   繁体   English

奇怪的重新分配行为

[英]Strange realloc behaviour

i'm developing an array structure just for fun. 我正在开发一个数组结构,只是为了好玩。 This structure, generalized by a template parameter, pre allocates a given number of items at startup, then, if "busy" items are more than available ones, a function will realloc the inner buffer . 这种由模板参数概括的结构在启动时会预先分配给定数量的项目,然后,如果“繁忙”项目多于可用项目,则函数将重新分配内部缓冲区。 The testing code is : 测试代码为:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

template <typename T> struct darray_t {
    size_t items;
    size_t busy;
    T     *data;
};

#define DARRAY_REALLOC_ITEMS_STEP 10

#define da_size(da) (da)->busy

template <typename T>
void da_init( darray_t<T> *da, size_t prealloc ){
    da->items = prealloc;
    da->busy  = 0;
    da->data  = (T *)malloc( sizeof(T) * prealloc );
}

template <typename T> T *da_next( darray_t<T> *da ){
    if( da->busy >= da->items ){
        da->data   = (T *)realloc( da->data, sizeof(T) * DARRAY_REALLOC_ITEMS_STEP );
        da->items += DARRAY_REALLOC_ITEMS_STEP;
    }
    return &da->data[ da->busy++ ];
}

int main(){
    darray_t<int> vi;
    int *n;

    da_init( &vi, 100 );

    for( int i = 0; i < 101; ++i ){
        n = da_next(&vi);
        *n = i;
    }

    for( int i = 0; i < da_size(&vi); ++i ){
        if( vi.data[i] != i ){
            printf( "!!! %d != %d\n", i, vi.data[i] );
        }
    }

    return 0;
}

As you can see, i prealloc 100 integer pointers at the beginning and then i realloc them with 10 more pointers at time. 如您所见,我在开始时预分配了100个整数指针,然后一次又分配了10个指针。 In the main function, i perform a for loop to check items integrity and, if an array item is not as i expect, i print its value and ... you know what ? 在主要功能中,我执行一个for循环来检查项的完整性,如果数组项不符合我的期望,我将打印其值,然后...您知道吗? I have the following message : 我有以下消息:

!!! 11 != 135121 11!= 135121

In fact, item at index 11, that should be '11', is 135121 !!!! 实际上,索引11处的项目应该为“ 11”,是135121 !!!! :S :S

Can you tell me if my code is not correct? 你能告诉我我的代码不正确吗?

Thanks 谢谢

NOTE I perfectly know that mixing C and C++ this way is ugly , and i know too that this structure would screw up if used, for instance : 注意:我完全知道以这种方式将C和C ++混合起来很丑陋 ,而且我也知道,如果使用这种结构,则会搞砸,例如:

darray_t<std::string>

This is just a test for int pointers. 这只是对int指针的测试。

realloc does not automatically grow the piece of memory - you'll have to do that. realloc不会自动增加内存-您必须这样做。 Do eg: 例如:

da->data=(T*)realloc(da->data, sizeof(T)*(da->items+DARRAY_REALLOC_ITEMS_STEP));

(and you should handle realloc returning NULL) (并且您应该处理realloc返回NULL)

The size of the block is incorrect: 块的大小不正确:

da->data   = (T *)realloc( da->data, sizeof(T) * DARRAY_REALLOC_ITEMS_STEP );

The entire block is as big as the increment. 整个块与增量一样大。 Try 尝试

da->busy + sizeof(T) * DARRAY_REALLOC_ITEMS_STEP

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM