Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

c++ - How to use memcpy correctly with different types of arrays

I have a templated class named Stack that has a private method resize.

Whenever I use the int or double template version of this class, it works as desired. But, whenever I use the float or string versions of the template, it crashes. I believe that it's a problem with my memcpy function call. How am I supposed to use it correctly?

template <class Type>

void Stack<Type>::resize(int capacity) {
    if(capacity >= MAX_SIZE)
        capacity = MAX_SIZE;

    Type* copy = new Type[capacity];

    for (int i = 0; i < N; i++) {
        copy[i] = s[i];
    }

    s = new Type[capacity];

    memcpy(s, copy, sizeof(Type) * capacity);

    size = capacity;

    delete copy;
}

s is a heap allocated member variable array of type Type.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First of all, it is incorrect to use memcpy to copy non-POD types. Just use a for loop, or std::copy.

Second, you are doing more work than necessary (and you have a memory leak).

void Stack<Type>::resize(int capacity) {
    if(capacity >= MAX_SIZE)
        capacity = MAX_SIZE;

    Type* copy = new Type[capacity];

    for (int i = 0; i < N; i++) {
        copy[i] = s[i];
    }

Up to this point, you're okay. You've allocated a new array, and assigned over the elements from the old array. I'm assuming N is the number of valid elements.

s = new Type[capacity];

Assuming that s previously pointed to an allocated array, this is a memory leak. First, you need to delete the previous data.

delete [] s;

Then, you don't need to allocate another array. Use the one you just allocated.

s = copy;

All together, the function now looks like this:

template <class Type>
void Stack<Type>::resize(int capacity) {
    if(capacity >= MAX_SIZE)
        capacity = MAX_SIZE;

    Type* copy = new Type[capacity];

    for (int i = 0; i < N; i++) {
        copy[i] = s[i];
    }

    delete [] s;
    s = copy;
    size = capacity;
}

If there are still problems, some other part of your code is broken.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...