title: How to allocate memory for a void pointer using new operator C++?
body: <p>So I am trying to make a linked list that can contain any data type at the same time. The list contains Element objects:</p>
  
  <pre><code>struct Element {
    void* data;
    Element* next;
  
    Element(const void* content, Element* next_ele) {
      next = next_ele;
      data = new void;  // this doesn't work
      (*data) = (*content)
    }
  };
  </code></pre>
  
  <p>The reason I have to allocate memory for <code>data</code> is because if I just assign <code>data = content</code>, if <code>*content</code> is destroyed (such as when leaving a local function), <code>*data</code> will also be destroyed. That means if I add some elements to the list inside a function, those elements will disappear from the list when the function exits. The example is below:</p>
  
  <pre><code>// in List.cpp
  List::add(void *content) {
      // for this question, ignore the case when list is empty 
      Element *ele = new Element(content, nullptr); 
      last.next = ele
      last = ele
  }
  
  
  // main.cpp
  List myList;
  
  void addEle() {
      int a; double b; char c;
      myList.add(&amp;a); myList.add(&amp;b); myList.add(&amp;c);
  }
  
  int main()
  {
      myList = newList();
      addEle();
  }
  </code></pre>
  
  <p>When addEle() exits, variables <code>a, b, c</code> doesn't exist anymore. So the content of the list is nonsense.</p>
  
  <p>So how can I allocate memory of void type in C++ to solve this problem? If I can't, is there any solution (except template) so that when I leave a local function, the content of a list isn't changed ?</p>
  
  <p>Thank you for your help.</p>
  
  <p>Edit 1: I can't use template because using template means each list object can only contain 1 data type. But I want to do something like myList.add(1), myList.add(3.5), myList.add('c'), myList.add(student), etc</p>