0

我正在编写一个函数,其作用类似于splicejs 中的函数:给定一个数组(任何类型),从给定索引开始删除一些元素,并在间隙中填充一些新元素(如果需要,扩展或缩小原始数组)。

我在 Windows7 下使用 MinGw/Eclipse CDT。这是我的代码:

void* splice(int typesize,void* arr,
        int size,int start, int length,
            void* stuff,int size2){
    //length is the number of elements to remove
    //and size2 is the number of elements to fill in the gap

    //so size-gap will be the size of the new array after the function
    //when gap is a minus number, the array grows
    //and when gap is a positive number, the array shrinks
    int gap = length-size2;
    void* ptr = malloc(typesize*(size-gap));//--------(1)--------
    if(ptr==NULL){
        puts("error");
        return NULL;
    }
    //now the ptr array is empty, copy the original array(arr)
    //to the ptr until the 'start' index
    memmove(ptr,arr,typesize*start);

    //fill the new array 'stuff' into ptr starting from 
    //the index after 'start'
    memmove(ptr+typesize*start,stuff,typesize*size2);

    //and copy the rest of the original array (starting from 
    //the index start+length, which means starting from 'start' index
    //and skip 'length' elements) into ptr
    memmove(ptr+typesize*(start+size2),arr+typesize*(start+length),
            typesize*(size-start-length));

    return ptr;
}

我还写了一些测试代码,下面的代码片段是针对long long类型的:

int main(){
    setbuf(stdout,NULL);
    int start = 1;
    int delete = 6;
    long long* oldArray= malloc(sizeof(long long)*7);
    long long* stuff = malloc(sizeof(long long)*3);
    oldArray[0]=7LL;
    oldArray[1]=8LL;
    oldArray[2]=4LL;
    oldArray[3]=1LL;
    oldArray[4]=55LL;
    oldArray[5]=67LL;
    oldArray[6]=71LL;
    stuff[0]=111LL;
    stuff[1]=233LL;
    stuff[2]=377LL;
    int newsize = 7-(delete-3);
    void* newArray = splice(sizeof(long long),oldArray,7,start,delete,stuff,3);
    if(newArray){

        //------------crash happens here-----------
        //free(oldArray);
        //-------------

        oldArray =  newArray;
        int i=0;
        for(;i<newsize;i++){
            printf("%I64d\n",oldArray[i]);
        }
    }
    return 0;
}

它应该输出 7、111,233 和 377(从索引 1 中删除六个元素并将 111,233 和 377 填充到数组中)。

我测试了 char、int 和 long 类型数组,并且在所有情况下代码都有效。除了一个问题:我无法释放旧数组。似乎内存块被多次访问后就无法回收了memmove

如果我在 (1) 处将 malloc 更改为 realloc 并且 free() 不会崩溃,但我不能再使函数正常工作(而且我不确定 free() 函数是否真的工作)。

请就这个问题是如何出现的以及如何改进我的代码提供一些建议。

4

1 回答 1

3

看看这一行:

    memmove(ptr,arr,typesize*size);

它尝试将 typesize * size 字节移动到 ptr。但是您只分配了 typesize*(size - gap) 字节。如果 gap > 0 这将导致崩溃,除非你很不走运。

我发现第一个错误后就停止了检查,所以可能还有更多,我没有费心去找出代码的作用。您应该添加一条评论,描述该功能应该做得足够好,以便我可以在不猜测或问您问题的情况下实现它。

于 2014-11-28T15:57:17.820 回答