1

In c, when defining a variable like int a; int* b;, memory is allocated in stack. When using malloc, heap memory is used.

My question is, if in a function like the one below:

void* function () {
int counter = 0;
while() {
   ... does some counting
   counter++;
}
return (void *) counter;
}

It is returning a pointer to counter, where does the memory of counter live? The code segment?

Junbang Huang
  • 1,927
  • 19
  • 26
  • Possible duplicate of [C function memory allocation](https://stackoverflow.com/questions/11406576/c-function-memory-allocation) – roottraveller Sep 01 '19 at 07:30
  • It is not returning a pointer to `counter`. It is converting the value of `counter` to a `void *`. That will be an invalid pointer, in the sense that any usage of it gives undefined behaviour. So it doesn't have to "live" anywhere in memory. – Peter Sep 01 '19 at 07:46

1 Answers1

2

It is not returning a pointer to counter. That would be &counter, which is a pointer to a local variable. Doing that would be an error because local variables are destroyed as soon as the function returns, so the caller would be left with a pointer to a thing that no longer exists.

In practice, counter probably lives on the stack or in a register (or several registers). The code segment is usually read-only, so variables couldn't live there.

(void *)counter is converting a number to a pointer value. The results of that operation are implementation-defined.

For example, with gcc:

A cast from integer to pointer discards most-significant bits if the pointer representation is smaller than the integer type, extends according to the signedness of the integer type if the pointer representation is larger than the integer type, otherwise the bits are unchanged.

The resulting address may not be a valid pointer value at all, or it may point to an unmapped page.

melpomene
  • 84,125
  • 8
  • 85
  • 148