|
-
May 21st, 2008, 06:49 AM
#2
Re: pointers and memory ...pls clarify
About the first case, in your function 'func' the int *p is a function's local variable, meaning the variable p (which is a pointer) is created on function stack, now ideally one should allocate memory and then assign the address of it to this pointer so that it points to a valid memory location, but in your case the pointer p is not pointing to any valid memory location, it will have some garbage address value stored in it (as it is a local variable) and then that garbage address will be used to store the value '10', which is a memory write violation (by chance the garbage address might be a valid address value, thus it is not necessary for your code to show an error when run), but in ideal case when you have code like following,
Code:
void func()
{
int *p = new int; // required to allocate memory first before storing any value.
*p = 10;
......
......
}
then the variable p is created on function stack and the new int is created on application heap, and then this new int's location (address) is assigned to p, so now when you assign 10 to this location is will be stored on heap, when the function exits, the memory allocated still stays there as you have not deleted it, so the value 10 will also stay there at that address, but as the variable p is local to function it will be cleared (because the function stack will be reverted back to previous Or caller function) you will effectively loose the address of the allocated memory, thus creating a memory leak of one int.
Regards,
Ramkrishna Pawar
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|