开发者

problem with passing custom array to function (c++)

I have an array of type T which I pass as a pointer parameter to a function. The problem is that I can't write new data to this array properly, without getting memory violation at the second try.

In this code I 开发者_如何学Goread integers from a text file and pass them to the function (part of template class of type T), in order to append them to the array.

After I finish to append the integers, I want to use the same array back in the Main.

Does someone know what's wrong with the code?

Thanks, Max

template<class T> int CFile<T>::read(T **apBuf, int aNum)
{
int readCounter = 0;

*apBuf = (T*)malloc(sizeof(T)*aNum);


for (int i = 0; i<aNum; i++)
{
    T var = read();

    if (var == NULL)
    {
        if (isEof)
        {

            return readCounter;
        }
        else
        {
            perror ("Error Reading File - Insufficient var type");
            return -1;
        }
    }
    else
    {   
        *apBuf[i] = var;

        readCounter++;
    }
}



return readCounter;

}


*apBuf[i] = var;

This is parsed as if it was written:

*(apBuf[i]) = var;

This is obviously not what you want; apBuf is a pointer to a pointer to an array; you are treating it as a pointer to an array and you are dereferencing the ith element of it. What you really mean is:

(*apBuf)[i] = var;

*apBuf gives you "the object pointed to by apBuf," which is the array; then you obtain the ith element of the array.

That said, this is rather unusual: why not accumulate the data into a std::vector<T> and return that from the function? Then you don't have to worry about the explicit dynamic memory management. (Also, is T always a pointer type? If not, then var == NULL makes no sense.)


Well, you used malloc to allocate the array, and then tried to assign to it. This is undefined behaviour, because you have to construct the objects.

Oh, and you should really, really consider using self-owning resource classes, because malloc and this style of programming in general is hideously unsafe. What if T's copy constructor throws an exception? Memory leak. Just for example.


One issue you have is your using malloc instead of new. If T is a class the constructor won't be called.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜