(C ++) What happened to the array allocated on the stack when the function is finished?

I come from many years of development in Java, and now that I need to switch to C ++, it is difficult for me to understand the memory management system.

Let me explain the situation with a small example:

In my opinion, you can allocate space either on the stack or on the heap. The first is done by declaring the variable as follows:

 int a[5]

or

int size = 10;
int a[size]

Conversely, if you want to allocate memory on the heap, you can do this using the "new" command. For example, for example:

int *a = new int[10]; (notice that I haven't tried all the code, so the syntax might be wrong)

One of the differences between them is that if it is allocated on the stack when the function is completed, the space is automatically freed, and in the other case, we must explicitly free it with delete ().

Now suppose I have a class like this:

class A {
  const int *elements[10];

  public void method(const int** elements) {
    int subarray[10];
    //do something
    elements[0] = subarray;
  }
}

:

  • . , [0], ? ( )?
  • subarray "const", . ? , const , .
  • (, , ), , "" 10 , , . , ?

( - C), ++ Java, . !

+4
6

A) , , undefined. Java, . :

int a = 4;
obj.foo(a);

a foo? , , , , . , , , . , , (--) , .

B) const, , const.

int b = 3
const int * const ptr = &b;
^            ^
|            |- this const marks the ptr itself const
| - this const marks the stuff ptr points to const

C) ++, .

+2

a), . , [0], ? ( )?

" undefined", . , subarray, , , , , . . . "undefined behavior" -land.

b) subarray "const", . ? , , .

.

const int * p1; // 1
int const * p2; // 2
int * const p3; // 3
int * p4;       // 4
int const * const p5; // 5

++. 1 , const int. 2 , 1 ( ). 3 , const mutable int. 4 , mutable int. 5 , const const int. : , , , .

c) , "" 10 , , . , ?

, , (.. , ).

, Java, . , void A::method(const int**) , . , . (, A), . , ++ , . , , , std::vector . , ( rvalue, ). "" / .

+2

Java C/++ - Undefined (UB). UB C/++. UB " " , UB , . , C/++ , UB, , .

, " ", - , , UB, , , , NULL ( UB), NULL , , .

UB ( ), , " ".

1) UB , . ? , . . , , .

2) :

int * a;                        // Non const pointer to non const data
int const * b;                  // Non const pointer to const data
int * const c = &someint;       // Const pointer to non const data
int const * const d = &someint; // Const pointer to const data

const * const * .

3) . C , ++ . , C . ++ ++ 11, , , : .

? , GCC. GCC. , C ++, " ". GCC, .

+1

, , . undefined , , , . ++ 3.7.3 1 ( ):

, , . , , .

0

a) , . , . , undefined!

b) Subarray - , . const, .

c) . . .

0

re a): When a function returns data, it is still where you put it on the stack. But this behavior is undefined to access it there, and this repository will be reused almost immediately. It will be reused the next time you call any function. This is due to how the stack is used.

0
source

All Articles