Finding Errors in Program Code

I am pretty new to C++ and need to figure out the issue(s) with these two segments of code:

1
2
3
4
5
6
7
8
9
10
11
12
void  funct( int *pt )
{
        .   .   .  
	delete  [ ] pt;
}

int  main
{
	int  *iptr   =   new  int[100];
	funct( iptr);
	return 0;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
char * funct(  )
{
	char * pt  =  new  char[200]; 
        .   .   .  
	return pt;
	}

int  main
{
	char  *cptr   =   new  char[100];
	cptr  =  funct( );
	return 0;
}


For the first segment of code, should the memory of pt not be released yet within the void function?
Last edited on
For the first segment of code, should the memory of pt not be released yet within the void function?
This is not a good idea. The caller of funct(...) might not expect that the passed data will be deleted. A better approach would be to free the memory on the level where it is acquired.

The best approach would be using smart pointer.

The secon segment produces a memory leak. The memory acquired on line 10 is never freed.
Does the first segment of code result in a dangling pointer?
Yes, this is what coder777 was referring to.

Dangling pointers arise during object destruction, when an object that has an incoming reference is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory.


After line 10 in the first snippet, iptr is no longer valid. However, to the casual observer of main(), it's not immediately obvious that iptr has been released.
Last edited on
Registered users can post here. Sign in or register to post.