Whats the Error

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

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.


*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.


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.


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

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:

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.


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.