Allocate memory then point it to another block


char * a = new char[200];
a = b;

Is the "new char [200]" still associated with "a" somehow? Or is the length of the block that "b" points to now applied to a ?
Last edited on
No. This is a memory leak. You no longer have a pointer that points at that char array. It's lost forever.
Also, while I'm here, by all means learn about new and delete, but don't use them. Don't use new and delete. Don't use new and delete.
I know about new and delete. Why shuldn't I use them?
You can use them ... just don't do what you have done here and "lose" the unnamed memory that you created on the heap.

Where you could use vector etc it may be better to use those because they have inbuilt destructors that will free the resource properly.

I wouldn't go so far as to say don't use them. Some good uses include:
- data structures like trees;
- any parallel processing with distributed memory;
- mixed-language processing; other languages won't recognise c++'s STL

Just use them with care. A delete for every new, and don't assign a pointer away from your anonymous block of memory without making sure that another pointer is directed at it.
If the first address of 200bytes space created by 'new' is 0x0001.

address 0x0001 that POINTER 'a' pointed is missed after 'a=b';
because only POINTER 'a' knew the address(0x0001). but now nobody knows.
this is a memory leak. nobody points 0x0001. so you can't delete the 200byte space.
200byte space in heap is still live until the program end.




Last edited on
I know about new and delete. Why shuldn't I use them?


Because there are safer, better alternatives. In your code above, you made a memory leak. As code gets more complicated, this gets easier and easier to do, and then when we throw exceptions into the mix, it becomes even easier. Using new and delete is a way to significantly increase the chances of making mistakes. Even if you get it right, in five years' time a successor programmer will add one new pathway, one new case, and in some place fifty files over where a delete becomes necessary, it won't be added and your code starts leaking five years after you left it in working condition. This happens every day in industry with full-time C++ programmers :/

The question isn't why shouldn't you use them; the question is why should you use them? You need a good reason to use new and delete instead of the safer, better alternatives (such as on the stack, containers, and smart pointers with make_unique and make_shared).

Good reasons do exist, but the default you reach for when you need dynamic memory shouldn't be new and delete. As a beginner, where simple, easy to remember rules are more helpful than lists of cases and considerations, a simple rule that covers most cases is "don't".

Yes, if you always used them perfectly, you could use them all the time without any trouble. No such programmer has ever existed.
Last edited on
If you stopped thinking in C, start thinking in C++, a lot of your "what happens when..." questions would disappear.

No need for C strings on the heap, let std::string do all the memory management for you. From construction to destruction without you worrying .
Hello @Furry Guy,

As you now have msys and the MinGW compiler suite you can try some mixed-language programming. This particular example is rather contrived (and it's harder to do it with char arrays), but I can assure you that there are plenty of people mixing languages all the time with numerical arrays.

C-strings are necessary here. There is absolutely no way to pass the arguments between programming languages as std::string. Both C++ and Fortran can be object-oriented ... but their classes are incompatible. However, basic arrays are easily passed.



============ Call Fortran from C++ =============

gfortran -c -fno-underscoring prog3a.f90
g++      -c                   prog3b.cpp
rem alternatives for linking ...
rem gfortran -o test.exe prog3a.o prog3b.o -lstdc++
    g++      -o test.exe prog3a.o prog3b.o -lgfortran -lquadmath


prog3a.f90 (Fortran)
1
2
3
4
5
6
7
8
9
10
subroutine addstrings( c, nc, a, na, b, nb ) bind( C, name = "addstrings" )
   use iso_c_binding
   implicit none
   integer, value :: na, nb, nc
   character a(na), b(nb)
   character c(nc)

   c = [ a, b, C_NULL_CHAR ]

end subroutine addstrings

prog3b.cpp (C++)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
extern "C" void addstrings( char *c, int nc, char *a, int na, char *b, int nb );
#include <iostream>
#include <cstring>

int main()
{
   const int SIZE = 80;
   char a[] = "Hello";
   char b[] = " World!";
   char c[SIZE];

   addstrings( c, SIZE, a, strlen(a), b, strlen(b) );    // calls a Fortran routine
   std::cout << c << '\n';
}

======================================




============ Call C++ from Fortran =============

gfortran -c -fno-underscoring prog4a.f90
g++      -c                   prog4b.cpp

rem alternatives for linking ...
rem gfortran -o test.exe prog4a.o prog4b.o -lstdc++
    g++      -o test.exe prog4a.o prog4b.o -lgfortran -lquadmath


prog4a.f90 (Fortran)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
module help        ! some compilers need an explicit interface
   use iso_c_binding

   interface
      subroutine addstrings( c, a, b ) bind( C, name = "addstrings" )
         character a(*), b(*)
         character c(*)
      end subroutine addstrings
   end interface

end module help


program main
   use help
   implicit none
   character(len=:), allocatable :: a, b
   character(len=80) c

   a = "Hello"   // C_NULL_CHAR
   b = " World!" // C_NULL_CHAR
   call addstrings( c, a, b)                ! calls a C++ routine
   write( *, * ) c(1:scan(c,C_NULL_CHAR)-1)

end program main

prog4b.cpp (C++)
1
2
3
4
5
6
7
8
extern "C" void addstrings( char *c, char *a, char *b );
#include <cstring>

void addstrings( char *c, char *a, char *b )
{
   strcpy( c, a );
   strcpy( c + strlen(a), b );
}

======================================



Give @volang a chance! It's Christmas and he/she only wants to know how things work.
Last edited on
A beginner who wants to mix C with C++ before they have a solid understanding of using C++ can develop bad habits that will end up hurting their understanding.

Two particular myths about C++ come to mind (out of the 5 most common):

Myth 1: "To understand C++, you must first learn C"
https://isocpp.org/blog/2014/12/myths-1

Myth 4: "For efficiency, you must write low-level code"
https://isocpp.org/blog/2014/12/myths-3
Topic archived. No new replies allowed.