I
I
Ivan2017-10-03 16:00:10
linux
Ivan, 2017-10-03 16:00:10

Where are the variables located in this case (stack, heap)?

The GMP (GNU Multiple Precision) library has a type definition for working with integers:

typedef struct {
  int _mp_alloc;	
  int _mp_size;
  mp_limb_t *_mp_d;
} __mpz_struct;

typedef __mpz_struct mpz_t[1];

When declaring a type variable mpz_t var;inside a function, the pointer to the structure will be clear on the stack, and the array pointed _mp_dto on the heap. And where will the _mp_alloc, _mp_sizeactual pointer value be placed _mp_d? This question is related to another: if the function is return (__mpz_struct *)var, then when exiting it (and, accordingly, clearing the stack), won't these values ​​be overwritten? Are there any guarantees on this subject in the standard, or does it all depend on the implementation of the compiler?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2017-10-03
@32seph

You are absolutely right. This is an array of one element, and in this arrangement it will be on the stack. With all its fields: alloc, size and mp_d. When exiting the function, there are chances that it will be overwritten, and this cannot be done.
Who will rub? Yes, anyone. Though the driver who wished to use your stack. Though the subsequent call of any function.
On the other hand, the __mpz_struct structure is marked with two underscores so that it is not used.

__mpz_struct* foo()
{
    mpz_t var;
    return (__mpz_struct *)var;
// C:\TestApps\RetLocal\main.cpp|15|warning: address of local variable 'var' returned [-Wreturn-local-addr]|
}

And this is how it works: everything is in a heap. Just don't forget to clear with delete[].
__mpz_struct* bar()
{
    __mpz_struct* var = new mpz_t;
    return var;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question