简体   繁体   中英

Access violation when “resizing” array in C++

So I'm trying to create a function that "resizes" a member array to a new size passed as an argument. By "resize", I mean that it should set the member array to a new array with the new size, copy over the elements from the old array, and then deallocate the memory associated with the old array. Here's what I have so far:

void MemoryTest::resize(unsigned int new_size) {
    if (size == new_size)
        return;

    int* oldPtr = elements;

    elements = new int[new_size + 1];
    for (int i = 0; i < (new_size < size) ? new_size : size; i++)
        elements[i] = oldPtr[i];

    elements[new_size] = '\0';

    if (size > new_size)
        size = new_size;

    delete[] oldPtr; // Deallocate old elements array
}

elements is a private member int* initialized to NULL.

However, when it begins the for loop, the program hangs for awhile before giving an Access Violation for the elements[i] = oldPtr[i] line. Someone please correct me if I'm wrong (which I probably am), but my understanding is that oldPtr should be a pointer pointing to the same initial point as elements. Then, I set elements equal to a new array, so the two are now pointing to two different things. Then I iterate through elements, setting each item equal to its counterpart in the old array.

Also, while I would normally use a vector to avoid situations like this, I'm trying to become more familiar with pointers and memory allocation in C++.

Thanks in advance!

for (int i = 0; i < (new_size < size) ? new_size : size; i++)

should read

for (int i = 0; (i < (new_size < size)) ? new_size : size; i++)

So, for (int i = 0; i < ((new_size < size) ? new_size : size); i++) should correct your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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