Whats the Error

for an assignment we have to find errors in the code
here is code
1
2
3
4
5
6
7
8
	
	
	int *pint;
	pint = new int;
	if (pint==NULL)
		*pint=100;//is this the error *pint should be pint???
	else
		cout<< "memory allocation error\n";
You may replace :
*pint = 100;
with :
(*pint) = 100;
But I think "pint = new int()" is more accurate.
@JM

You have been told before - don't post advice to others, because you don't know what you are talking about.

Is it any wonder that people think you are a troll? Unless you behaviour changes, you are on a thin edge of being reported as such.

In this case, the use of parentheses does nothing at all.

@jkfde

*pint is OK, it fetches the integer value at the address pointed to by pint. pint is the pointer variable and contains a memory address. If you did pint = 100; this would attempt to assign 100 to the pointer, which should result in an error.

http://www.cplusplus.com/doc/tutorial/pointers/


The first problem is that if the new operator fails, then C++ would throw an exception, making any later error trapping code pointless. To fix this you would need to enclose line 4 in a try / catch block and catch the exception yourself. Mind you if this happens, you have much bigger problems I think.

http://www.cplusplus.com/doc/tutorial/exceptions/


In my mind, error processing should be done first then code is allowed to continue if everything is OK:

1
2
3
4
if(there-is-an-error) {
//process the error
}
//everything OK, so continue 


The example in your post is backwards in this respect.

The declaration / initialisation of the pointer can all be done on one line, and you can put this in the try block:

1
2
int *pMyInt = new int(100);



The use of NULL is discouraged because it is not type safe and is sometimes interpreted as 0 or a pointer to void. C++11 has nullptr which is designed to fix this problem. Although you shouldn't need this in the code if exceptions are being used, just added it for your education.


http://www.cprogramming.com/c++11/c++11-nullptr-strongly-typed-enum-class.html


Hope all this helps.
The code is saying that if pint is null, dereference it and set what it points to equal to 100. Otherwise, if pint is not null, then there was a memory allocation error. Does this seem right to you?

Edit: just to clarify, neither of the things Jackson Marie posted are actual errors. The code may be clearer with those changes, but they aren't errors that your professor would be looking for.
Last edited on
Topic archived. No new replies allowed.