How about pointer scope in funtion?

1
2
3
4
5
6
7
8
9
void functionA()
{
int *p = new int;
}

void functionB()
{
int *p = new int;
}


Is "p" in functionA point to the same address on "p" in functionB?
Any problem to declare same pointer name on difference function like this?
Is "p" in functionA point to the same address on "p" in functionB?
No

Any problem to declare same pointer name on difference function like this?
Yes: memory leak. After p falls out of scope the memory pointed to is no longer accessible
Its not a problem to reuse variable names in different functions.

however, as coder777 said, your example needs to "delete p" before it exits, otherwise the "new int" is left laying around in memory, this is called a memory leak. If you called this function 1000 times it would leave 1000 int's.
So whatever declare in each function will have it's own address even pointer. Right?
In this case, Is there any chance for pointer to point to the same address?
Last edited on
Is there any chance for pointer to point to the same address?

That depends.

As you've coded it, no because the memory is never released.

If you properly release the memory, then yes, it is possible that a subsequent allocation could return the address of memory that was previously allocated and subsequently released. That should not be a problem because when you release it, you are saying that you will no longer reference that memory.

Topic archived. No new replies allowed.