1

Let's suppose I have an object of a class as shown below:

Myclass obj;

Now I want to store this object to my desired memory location. How can I do this? Is it possible or not?

I have created an array class which simply insert data of integer type in respective indexes but the size of array is not declared inside the class. I insert small amount of data like 50 to 60 integers , then I use loop to insert a large data inside this class, but this time my program crashes , I think it is because of reason that if some index is encountered in memory which has some value in it , program stops itself. Now I want to analyze the memory that my object of array class start from that particular address which contain maximum number of available empty useable memory spaces

I think it is not allowing more insertions because of some allocated memory location. Now I want to place my object on that memory address which contain maximum available empty useable space. Please guide me

#include<iostream>
using namespace std;

class newarray 
{
public:
    int n;
    int arr[]; //size not declared 
    int* ptr;

    newarray():n(0),ptr(NULL)
    {
    }

    void getadress(int indexno) //for getting address of an index
    {
        ptr=&arr[indexno];
        cout<<endl<<ptr;
    }

    void insert(int a) //inserting an element
    {
        arr[n]=a;
        n++;
    }

    void display()
    {
        for(int i=0;i<=n;i++)
        {
            cout<<endl<<arr[i];
        }
    }
};

int main()
{
    newarray a1;
    int x=1;

    for(int i=0;i<100;i++) //work good with 100 inssertions
    //but if exceed to 300 or more it crashes.
    {
        a1.insert(x);
        x++;
    }
    a1.display();
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Hassan Ali
  • 35
  • 8
  • Your question seems to be missing something. What do you want to do? Control some hardware directly? (https://www.youtube.com/watch?v=EM83l5NZ15c). If it is because you think you loaded an object (from) disk at that memory. Use placement new (don't reinterpret_cast) – Pepijn Kramer Jan 17 '22 at 09:12
  • On a generic PC-like system? No it's not really possible (for user-space applications). On small embedded systems? Yes it's common. – Some programmer dude Jan 17 '22 at 09:12
  • With placement new, you can create (initialize) an object wherever you want. – Daniel Langr Jan 17 '22 at 09:13
  • Where do you want to store it (and why)? Do you want to save it's member variable values to disk to reload another time or do you mean something else? – doctorlove Jan 17 '22 at 09:15
  • 2
    In its current form, this question is an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Why do you need to store an object at a specific address? What is the address you need to store it on? Is this a user-space program on a PC-like system? Is for an embedded system? Also please take some time to read [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). And please learn how to [edit] your question to improve it. – Some programmer dude Jan 17 '22 at 09:19
  • 1
    Can you give an example of a memory location? And describe on what operating system/hardware this would be running – Sebastian Jan 17 '22 at 10:18
  • I have created an array classi which simply insert data of integer type in respective indexes but the size of array is not declared inside the class. I insert small amount of data like 50 to 60 integers , then I use loop to insert a large data inside this class, but this time my program crashes , I think it is because of reason that if some index is encountered in memory which has some value in it , program stops itself. Now I want to analyze the memory that my object of array class start from that particular address which contain maximum number of available empty useable memory spaces. Help – Hassan Ali Jan 17 '22 at 11:51
  • 1
    Where do you think the memory for `arr` is coming from? – Stephen M. Webb Jan 17 '22 at 12:26
  • I think the compiler randomly put it into some contiguous memory location without allocating a block or any specific size of memory. Correct me if I'm wrong. – Hassan Ali Jan 17 '22 at 12:29
  • 1
    `int arr[];` is not allowed in C++. For an array you *must* specify a size that is a compile-time constant. If you want a "dynamic array" you should use `std::vector`. – Some programmer dude Jan 17 '22 at 13:44
  • 1
    On another note, don't create member variables that should only be local variables inside a function. The `ptr` variable doesn't need to be a member variable, it should be defined as a local variable inside the `getadress` function (and isn't even needed there). – Some programmer dude Jan 17 '22 at 13:46
  • @Someprogrammerdude Yes this is correct ptr variable isn't necessary – Hassan Ali Jan 17 '22 at 14:11

5 Answers5

2

You can initialize an object to a specific memory location by using the new operator with a memory address like so:

MyObject *obj = new(address) MyObject(arguments);

Note that when using "new" like this, you will probably need to call the destructor manually to run its logic.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
shaked cohen
  • 101
  • 1
  • 4
  • 4
    Note that this is so-called _placement new_, which is a form of the _new expression_. `operator new` is something else. – Daniel Langr Jan 17 '22 at 09:14
  • 4
    Also you *don't* `delete` things that were constructed by placement new, you `obj.~MyObject()` them (separately from releasing `address`) – Caleth Jan 17 '22 at 09:16
  • Thanks @Caleth, you are right. I fixed the answer. – shaked cohen Jan 17 '22 at 09:17
  • I have created an array classi which simply insert data of integer type in respective indexes but the size of array is not declared inside the class. I insert small amount of data like 50 to 60 integers , then I use loop to insert a large data inside this class, but this time my program crashes , I think it is because of reason that if some index is encountered in memory which has some value in it , program stops itself. Now I want to analyze the memory that my object of array class start from that particular address which contain maximum number of available empty useable memory spaces. Help – Hassan Ali Jan 17 '22 at 11:52
1

In case of a variable, you never have an option to choose the memory location. The language implementation takes care of that for you, and in ideal cases might even not use any memory at all.

In case of dynamic objects, it is possible to create an object in a memory location of your choice - but there are limitations: On memory mapped systems (i.e. any modern operating system), you are restricted to only use memory that you have allocated. You generally cannot choose the memory addresses where allocations are, but you get to choose within the allocation, where to create dynamic objects - so long as the address satisfies the alignment requirements of the type. There are many ways of allocating memory, provided both by the C++ standard and by the operating system.


An embedded system might be one where memory isn't mapped. There, you don't have an operating system from which you could or would need to allocate memory.

On such system, if you are in control of the hardware, you will know which memory addresses in which you can safely create objects by virtue of knowing how you set up the hardware. If you don't know how the hardware is set up, then you must read the documentation.

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

You can't choose an arbitrary address in memory-mapped systems and store an object there. You need to first allocate a buffer (for example using new[]) and then construct your object in that pre-allocated buffer using placement new.

Here is a simple example:

#include <iostream>
#include <cstddef>


class Myclass
{
public:
    int m_value;
};

int main( )
{
    std::byte* buffer  = new std::byte [ sizeof( Myclass ) ]; // allocate a buffer
    Myclass* ptr = new ( buffer ) Myclass( 123 ); // construct the object in
                                                  // that buffer

    std::cout << ptr->m_value << '\n'; // print the value for
                                       // demonstartion purposes

    ptr->~Myclass( ); // explicitly call the destructor
    delete [ ] buffer; // release the buffer
}

Now back to the bug in your code. The problem is that your arr does not have a fixed size. That's not good. Instead of that use a std::vector so that it can extend itself at run-time by inserting elements at its back.

Here is the fixed version of your program:

#include <iostream>
#include <vector>


class NewArray
{
public:
    NewArray( )
    : arr( 0 )
    {
    }

    void getAddress( const std::size_t idx ) // for getting address of an index
    {
        std::cout << '\n' << &arr[ idx ];
    }

    void insert( const int elem ) // inserting an element
    {
        arr.push_back( elem );
    }

    void display( )
    {
        for( const auto& elem : arr )
        {
            std::cout << '\n' << elem;
        }
    }

private:
    std::vector<int> arr;
};

int main( )
{
    NewArray a1;
    int num { 1 };

    for ( std::size_t i { }; i < 100; ++i )
    {
        a1.insert( num );
        ++num;
    }

    a1.display( );
}
digito_evo
  • 3,216
  • 2
  • 14
  • 42
  • 1
    A small nitpicky thing: You should use `char`, `unsigned char` or even better `std::byte` for buffers where you use placement new (those are allowed by the standard, otherwise UB). `uint8_t` is not guaranteed to be `unsigned char`. – Sebastian Jan 17 '22 at 11:25
  • I have created an array classi which simply insert data of integer type in respective indexes but the size of array is not declared inside the class. I insert small amount of data like 50 to 60 integers , then I use loop to insert a large data inside this class, but this time my program crashes , I think it is because of reason that if some index is encountered in memory which has some value in it , program stops itself. Now I want to analyze the memory that my object of array class start from that particular address which contain maximum number of available empty useable memory spaces. Help – Hassan Ali Jan 17 '22 at 11:51
  • 1
    @Hassan Ali It's hard to tell anything without you providing a minimal reproducible example in your question. Please edit your question and add the relevant code so that we can debug it. – digito_evo Jan 17 '22 at 11:54
  • 1
    I have attached the code now , – Hassan Ali Jan 17 '22 at 12:26
  • @Hassan Ali Check the answer. – digito_evo Jan 17 '22 at 12:35
1

You wrote

 class newarray 
    {
    int arr[]; //size not declared

This is not allowed. Unfortunately, your compiler did not warn you when compilinhg. You only discovered that this was a problem when your code crashed.

You then wonder about "some allocated memory location" and picking one manually. That's not the problem. int arr[] without explicitly specifying bounds is allowed only in a few contexts, such as a function declaration. The function declaration doesn't need a size because the size in that case is determined by the caller.

Since this is C++, just use std::vector<int> for your dynamic arrays.

MSalters
  • 173,980
  • 10
  • 155
  • 350
0

Objects have a unique memory adress. Once the object exists you cannot change where it is stored in memory. You can create a copy and store that copy elsewhere, but you cannot store that particular object in some other memory adress after it has been created.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185