-1

I have two piece of code that creates an A object

A* a=new A();

AND

A b; 
A *c=&b;

The question is: someone says "objects are always allocated on heap"?

Is it true even declare it on stack?(Code 1)

Note: I am referring to the actual memory allocation. I know object 'b' will be

cleared when it goes out the the scope. But when it is still in scope, where does the

memory of 'b' actually reside?

SDEZero
  • 363
  • 2
  • 13

4 Answers4

2

Pointer a is on stack, the instance of A it points to is on heap.

Object b is on stack, pointer c is on stack.

Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
kravemir
  • 10,636
  • 17
  • 64
  • 111
1

As a general rule of thumb:

If you use any kind of dynamic memory allocation (new, array new, malloc etc), the allocated object will be located on the heap. Else, it is pushed onto the stack.

Zultar
  • 183
  • 1
  • 9
1

@LouisTan it depends where these lines of code are located in program. But in general this pointer will be on Stack.

compare this:

/* my.c */

char * str = "Your dog has fleas.";  /* 1 */
char * buf0 ;                         /* 2 */

int main(){
    char * str2 = "Don't make fun of my dog." ;  /* 3 */
    static char * str3 = str;         /* 4 */
    char * buf1 ;                     /* 5 */
    buf0 = malloc(BUFSIZ);            /* 6 */
    buf1 = malloc(BUFSIZ);            /* 7 */

    return 0;
}
  1. This is neither allocated on the stack NOR on the heap. Instead it's allocated as static data, and put into it's own memory segment on most modern machines. The actual string is also being allocated as static data, and put into a read-only segment in right-thinking machines.
  2. is simply a static alocated pointer; room for one address, in static data.
  3. has the pointer allocated on the stack, and will be effectively deallocated when main returns. The string, since it's a constant, is allocated in static data space along with the other strings.
  4. is actually allocated exactly like at 2. The static keyword tells you that it's not to be allocated on the stack.
  5. ...but buf1 is on the stack, and
  6. ... the malloc'ed buffer space is on the heap.
  7. And by the way., kids don't try this at home. malloc has a return value of interest; you should always check the return value.

see here full Charlie Martin post

Community
  • 1
  • 1
4pie0
  • 29,204
  • 9
  • 82
  • 118
0

It is definite possible to create objects on local scope (using stack memory) just as you have shown on the second snippet.
The first snippet creates object A using heap memory.

Kevin

Kevin T.
  • 13
  • 1