Search code examples
c++new-operatorheap-memory

New allocates the same memory with each iteration


I am trying to build a list-like heap storage of C-strings. This is a simplified part of the program.

However, with each iteration new brings up the same address.

#include <iostream>

class listStringContainer {
public:
    listStringContainer(const char* c);//constructor
};

int main(){
    listStringContainer lsc1 ("Lorem ipsum");// calling the constructor
}

listStringContainer::listStringContainer(const char* c) {//constructor
    char * Memory_Address;

    auto time{5};
    while (--time>=0) {
            Memory_Address = new char[16];
            //the memory location is to be saved into a vector
            std::cout << "Memory_Address: "<< &Memory_Address << std::endl;
        }
}

Output:

Memory_Address: 0x62fed8
Memory_Address: 0x62fed8
Memory_Address: 0x62fed8
Memory_Address: 0x62fed8
Memory_Address: 0x62fed8

The same result on g++ and MSVS. Why does new appoint the same location and how to make new appoint different addresses?


Solution

  • You need to cast the static_cast<void*>(Memory_Address) to get the value stored in Memory_Address. Lets consider:

    char * p;
    p= new char[16];
    strcpy(p, "Hello");
    
    cout << *p << endl; // Prints 'H'
    cout << &p << endl; // Prints address of p
    cout << p << endl; // Prints "Hello"
    cout << static_cast<void*>(p) << endl; // Prints address of p[0]
    

    Consider the below same scenario but with Integer data type:

    int * ptr;
    ptr= new int[16];
    ptr[0] = 10;
    
    cout << *ptr << endl; // Prints 10
    cout << &ptr << endl; // Prints ptr address
    cout << ptr << endl; // Prints address of ptr[0]
    

    Therefore, Integer doesn't require casting to void* for getting &ptr[0]