operation "new"

What happens when run bellow code?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  // Example program
#include <iostream>
#include <string>

void create()
{
    for(;;){
     int *a = new int;   
     std::cout<<a<<std::endl;
     delete a;
    }
}
int main()
{
  create();
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  // Example program
#include <iostream>
#include <string>

void create()
{
    for(;;){
     int *a = new int;   
     std::cout<<a<<std::endl;
    }
}
int main()
{
  create();
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  // Example program
#include <iostream>
#include <string>

int * create()
{
     int *a = new int;   
    return a;
}
int main()
{
  for(;;){
  int *a=NULL;
  a=create();
  std::cout<<a<<std::endl;
  }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  // Example program
#include <iostream>
#include <string>

int * create()
{
     int *a = new int;   
    return a;
}
int main()
{
  for(;;){
  int *a=NULL;
  a=create();
  std::cout<<a<<std::endl;
  delete a;
  }
}
I would imagine that each program will go into an infinite loop while printing a memory address, as none of the for-loops have any method for ending.

What is it that you would like, or expect, to happen?
Last edited on
I want check operation "new" and "delete" to avoid memory leak
example 1 and 4 . are they the same??
Last edited on
I want check operation "new" and "delete" to avoid memory leak


The best way to do that, is to not use them. Learn about RAII, use STL containers like std::vector.

Good Luck!!
every new needs to be paired to a delete.
first block does this, second does not.
third does not, fourth does.

A new Foo does three operations:
1. Allocates memory from Free Store for Foo-type object.
2. Constructs Foo-type object in the allocated memory
3. Returns the address of the object

The lifetime of the object is not limited to the scope where it was created.
There is no "garbage collection"; object destruction and memory deallocation have to be done explicitly.

The delete address ; does two operations:
1. Destructs the object that is at address
2. Deallocates the memory block


What does happen, if you attempt to allocate infinite bytes of memory? Two of your examples do that.


RAII:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <memory>

auto create()
{
    auto foo = std::make_shared<int> (42);
    return foo;
    // foo goes out of scope
}

int main()
{
  for(int x=0;x<10;++x){
    auto bar = create(); // foo goes out of scope, but bar has a copy of pointer
    std::cout << *bar << std::endl;
    // bar goes out of scope; proper deallocation of the int
  }
}

Topic archived. No new replies allowed.