473,499 Members | 1,658 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is the peace of code valid according to standard?

I'm a student in a university and today we had a final exam in c++.
Basicly, I was amazed by the amount of lame and invalid
examples/questions.
There was a question that in practice works but is a really big mistake
(as far as I'm concerned). So, I'll need to prove why exactly it was
wrong. Here is the example:

int *p1, *p2, x = 3;
p1 = new int;
*p1 = 60;
cout << "A: " << x* *p1 << ' ' << *p1 << endl;
p2 = p1;
*p1 = 30;
cout << "B: " << x* *p1 << ' ' << *p2 << endl;
delete p1;
p1 = new int;
*p1 = 10;
cout << "C: " << *p1 << ' ' << x* *p2 << endl;

What is the output assuming code compiles well?
My solution was:
Program has undefined behavior
A: 180 60
B: 90 30
C: 10 (Boom!!!)
Access violation

However in practice default memory management routines allocate p1 at
the same place in this example (which makes this code run well) and p2
still points to the same area as p1;
Does standart say anything about addresses where each new allocates
memory? Basicly is this peace of code has undefined behavor or not?
(at least if I put another new int before p1 is reinitialazed I get
undefined output)

Thank you

Jul 23 '05 #1
8 1412
bl******@mail.ru wrote:
I'm a student in a university and today we had a final exam in c++.
Basicly, I was amazed by the amount of lame and invalid
examples/questions.
There was a question that in practice works but is a really big mistake
(as far as I'm concerned). So, I'll need to prove why exactly it was
wrong. Here is the example:

int *p1, *p2, x = 3;
p1 = new int;
*p1 = 60;
cout << "A: " << x* *p1 << ' ' << *p1 << endl;
p2 = p1;
*p1 = 30;
cout << "B: " << x* *p1 << ' ' << *p2 << endl;
delete p1;
p1 = new int;
*p1 = 10;
cout << "C: " << *p1 << ' ' << x* *p2 << endl;

What is the output assuming code compiles well?
Assuming that it's inside a function (say, 'main') and all the needed
headers have been included, the output is like you say, undefined.
My solution was:
Program has undefined behavior
A: 180 60
B: 90 30
C: 10 (Boom!!!)
Access violation
"Access violation" is just one of the [infinitely many] possible
behaviours.
However in practice default memory management routines allocate p1 at
the same place in this example (which makes this code run well) and p2
still points to the same area as p1;
I'll take your word for it.
Does standart say anything about addresses where each new allocates
memory?
Nope.
Basicly is this peace of code has undefined behavor or not?
Undefined.
(at least if I put another new int before p1 is reinitialazed I get
undefined output)


You get it even if you don't. It looks defined, perhaps, but it's not.

V
Jul 23 '05 #2
Thanks Victor. Now I'm sure about my answer.
This class is intro to c++, but on the 3-hr-long exam some idiot (aside
from this completely invalid question with pointers) asked to write
single-linked list, sort matrices, lot's of input/output (not to
mention that many questions were completely unclear). All this
paper-only exam where I wrote about 15-20 pages of code! and most of
the students never new what programming is before the class!
Is there a way to estimate required time to program task/assignment in
c++, provided the solution should be correct, it shouldn't use advanced
topics (no stl other than string! :)), e.g. even for a simple sort we
must manually write for(...) loops etc.
I have some experience with many progr. languages, my experience with
c++ is > 3 years and I barely had enough time to finish all the
questions. I feel that my university fucks the students in this class -
our teachers don't know c++ (at least my prof. directly told me that he
doesn't), so I wanna fill up some sort of protest to my department in
university to review profficency of the people who try to teach us.
Aside from the final half of our assignments had meaningless questions
and many solutions posted by the course maintaner are either really bad
or in some case plainly wrong (yeah, they give wrong output!!)
Is there any suggestion someone can give me?
Thanks

Jul 23 '05 #3
block...@mail.ru wrote:
Thanks Victor. Now I'm sure about my answer.
This class is intro to c++, but on the 3-hr-long exam some idiot (aside from this completely invalid question with pointers) asked to write
single-linked list, sort matrices, lot's of input/output (not to
mention that many questions were completely unclear). All this
paper-only exam where I wrote about 15-20 pages of code! and most of
the students never new what programming is before the class!
Is there a way to estimate required time to program task/assignment in c++, provided the solution should be correct, it shouldn't use advanced topics (no stl other than string! :)), e.g. even for a simple sort we
must manually write for(...) loops etc.
I have some experience with many progr. languages, my experience with
c++ is > 3 years and I barely had enough time to finish all the
questions. I feel that my university fucks the students in this class - our teachers don't know c++ (at least my prof. directly told me that he doesn't), so I wanna fill up some sort of protest to my department in
university to review profficency of the people who try to teach us.
Aside from the final half of our assignments had meaningless questions and many solutions posted by the course maintaner are either really bad or in some case plainly wrong (yeah, they give wrong output!!)
Is there any suggestion someone can give me?
Thanks


IMO, unless you go to a university known for computer science, don't
expect a good education in it. for example, I just got out of a
business college, and my major was Computer Systems Management (CS),
but none of the teachers really knew all that much about programming at
all... the one teacher we had that was really good at programming (and
comp sci in general) left after his first semester teaching because the
school wasn't up to his caliber.

Jul 23 '05 #4
Hi,
Does standart say anything about addresses where each new allocates
memory?


Just a minor point, but if you're concerned about the addresses used,
it might be worth looking at placement new. Just FYI..... that's all.

C++ FAQ...

"[11.10] What is "placement new" and why would I use it?

There are many uses of placement new. The simplest use is to place an
object
at a particular location in memory. This is done by supplying the
place as a
pointer parameter to the new part of a new expression:

#include <new> // Must #include this to use "placement new"
#include "Fred.h" // Declaration of class Fred

void someCode()
{
char memory[sizeof(Fred)]; // Line #1
void* place = memory; // Line #2

Fred* f = new(place) Fred(); // Line #3 (see "DANGER" below)
// The pointers f and place will be equal

// ...
}

Line #1 creates an array of sizeof(Fred) bytes of memory, which is big
enough
to hold a Fred object. Line #2 creates a pointer place that points to
the
first byte of this memory (experienced C programmers will note that
this step
was unnecessary; it's there only to make the code more obvious). Line
#3
essentially just calls the constructor Fred::Fred(). The this pointer
in the
Fred constructor will be equal to place. The returned pointer f will
therefore
be equal to place.

ADVICE: Don't use this "placement new" syntax unless you have to. Use
it only
when you really care that an object is placed at a particular location
in
memory. For example, when your hardware has a memory-mapped I/O timer
device,
and you want to place a Clock object at that memory location.

DANGER: You are taking sole responsibility that the pointer you pass
to the
"placement new" operator points to a region of memory that is big
enough and is
properly aligned for the object type that you're creating. Neither
the
compiler nor the run-time system make any attempt to check whether you
did this
right. If your Fred class needs to be aligned on a 4 byte boundary
but you
supplied a location that isn't properly aligned, you can have a
serious
disaster on your hands (if you don't know what "alignment" means,
please don't
use the placement new syntax). You have been warned.

You are also solely responsible for destructing the placed object.
This is
done by explicitly calling the destructor:

void someCode()
{
char memory[sizeof(Fred)];
void* p = memory;
Fred* f = new(p) Fred();
// ...
f->~Fred(); // Explicitly call the destructor for the placed
object
}

This is about the only time you ever explicitly call a destructor.

Note: there is a much cleaner but more sophisticated[11.14] way of
handling the
destruction / deletion situation.
Jul 23 '05 #5
On 20 Apr 2005 20:18:33 -0700, bl******@mail.ru
<bl******@mail.ru> wrote:
This class is intro to c++, but on the 3-hr-long exam some idiot (aside
from this completely invalid question with pointers) asked to write
single-linked list, sort matrices, lot's of input/output (not to
mention that many questions were completely unclear). All this
paper-only exam where I wrote about 15-20 pages of code! and most of
the students never new what programming is before the class!
It sounds like rampant[1] incompetance.

[1] As opposed to couchant or passant...
Is there a way to estimate required time to program task/assignment in
c++, provided the solution should be correct, it shouldn't use advanced
topics (no stl other than string! :)), e.g. even for a simple sort we
must manually write for(...) loops etc.
A competant teacher should be able to estimate how long it will
physically take to write the answers (in my case, if I had to write 16
pages of code by hand (not typing) it would take a long time quite apart
from any thinking time). If they aren't sure they can do trials with
small groups of students (or other teachers) to get better estimates.
I have some experience with many progr. languages, my experience with
c++ is > 3 years and I barely had enough time to finish all the
questions. I feel that my university fucks the students in this class -
our teachers don't know c++ (at least my prof. directly told me that he
doesn't),
Hold on, the person teaching "Intro to C++" doesn't know C++? What
'university' is this where the people teaching a subject don't know the
subject?
so I wanna fill up some sort of protest to my department in
university to review profficency of the people who try to teach us.
Too right. If they don't want to do anything, tell them that you are
going to publicise their incompetance (if they still don't, tell the
press). Is this a public-funded institution, or one where you are
paying for the tuition? If the former, inform the public bodies
responsible (and since it's public money, your government
representatives and the press); if the latter you can probably sue them
because it's your money (or your parents' or whoever).
Aside from the final half of our assignments had meaningless questions
and many solutions posted by the course maintaner are either really bad
or in some case plainly wrong (yeah, they give wrong output!!)
Is there any suggestion someone can give me?


Find a university where they know what they are teaching. Let it be
known what this so-called university is so that other students and
potential students don't go there (if they are incopetant in one subject
then they are probably incempetant in others as well.)

(Oh, and get documentation of their incompetance, so they can't raise a
slander or libel case against you...)

Chris C
Jul 23 '05 #6
In message <sl******************@ccserver.keris.net>, Chris Croughton
<ch***@keristor.net> writes
On 20 Apr 2005 20:18:33 -0700, bl******@mail.ru
<bl******@mail.ru> wrote:
This class is intro to c++, but on the 3-hr-long exam some idiot (aside
from this completely invalid question with pointers) asked to write
single-linked list, sort matrices, lot's of input/output (not to
mention that many questions were completely unclear). All this
paper-only exam where I wrote about 15-20 pages of code! and most of
the students never new what programming is before the class!


It sounds like rampant[1] incompetance.

[1] As opposed to couchant or passant...


Well, after all it's the peace of code which passeth all
understanding...

--
Richard Herring
Jul 23 '05 #7
Thanks for constructive feedback!
I study in computer engeneering and I don't expect good education the
university :), in this field practical experience makes big difference
and not education IMO.
Hold on, the person teaching "Intro to C++" doesn't know C++? What
'university' is this where the people teaching a subject don't know the subject?
:) it's unbelivable, but it's my conclusion after viewing solutions
posted by the course maintainer. Aside from ugly style the code is full
of
bool some_func(...){
....
int * a=new int[XXX];
if(a==0){
cout << "Unable to allocate memory" << endl;
return false;
} //this part seems to be copy-pasted everywhere :)
....
}

end then in every place code checks for return from some_func to be
true.
I short, it looks as though the course maintainer comes from old c
background, but I doubt that in such case she/he didn't know about
pointers/pointer arithmetics.
when in a medterm I needed to sort array of StudentInfo by GPA I wrote
struct StudentInfo{ ...; float GPA; ...;};
struct compareStudInfo{ bool operator()(stud1,stud2){return
gpa1<gpa2;}}
and then std::sort(arrayOfStudents, arrayOfStudents+numOfStudents,
compareStudInfo());
I got zero for the question because it seemed too short (my solution
was more compact than here) than they expected and they told me I
didn't solve the question, I tried to explain how it works, by the
teacher really had hard time understanding this code!!!

I personally believe intro to cpp for beginners should not teach
pointers etc. but rather start from stl containters (just as we were
taught std::string). Like when I studied java in college we started
right from oop

....About 16 pages of code... I was really afraid that I made a mistake
somewhere. For almost all the 3 hours I was writting (because this dumb
idiot wants for every class separate declaration and implementation, or
they're going to deduct marks). Imagine - they ask to write some class
with 3-4 members and 6-8 methods. All the methods have strange naming
convention (better say they don't have any naming conventions) and then
I needed to flip pages back and forth in order to copy the lines for
declaration to implementation... even int size()const{return _size;}
must be defined in *.h and implemented in *.cpp! In one place they
asked to write a few functions and to write a test program, one of the
functions was really difficult - I spent a big amount of time to
implement it and then I find out that at the bottom they say to assume
that this function is already implemented!!! :) I asked the teacher why
this function was mentioned then in the section asking what we need to
write - he found it strange himself :))

Hold on, the person teaching "Intro to C++" doesn't know C++? What
'university' is this where the people teaching a subject don't know the subject?


A friend of mine who took the class a semester before asked me to help
him to prepare for his final. Even at that time I told him that many
questions look like they were made by someone who also need to take
this course :), and my friend told me that the professor told the class
that he knows programming but doesn't know cpp and before he teaches
some subject in class he reads the book at home to learn it :)))
I'm paying tuition. I really wanted to get exemption from the course (I
was ready to write a final exam on the first day of the class) but it's
so complicated to get exemption - I already repeat math, calculus,
molecular phisics, chemistry :) (in total 13 classes). It was difficult
to proove that I already studied this material, since it was ~5 years
ago in school and of course I cannot write exam for many of the courses
cause I forgot this useless crap long time ago...

It's easy to say "sue them" :) I'm not that reach :) - only to fill out
peace of paper to the court costs 50$ or so (I live in canada). There's
also a funny thing - in "intro to computers" our university decided to
teach vb6! Course description says that it's kind of for thouse who
don't know what computers are :) (is vb6 for those who don't know what
computers are?), on the first day (and the last when I attended this
class) I recall teacher started to explaint something about bits and
bytes, then he said "one byte is ... aa--mmm, let me check, it's on xxx
page ... [he's looking in the book] ... I think it's 4 or 8 bits ...
oh, yes, here it is - one byte is 8 bit". I couldn't believe my ears!
At least the teacher himself said that vb6 is quite obsolete and by the
time when we finish university it will be of no use ...


And yes, I new about placement new (I programmed for a while before
entering university :)), but it's not related to the original question
IMO. I also had in one case to call destructor myself :) in a fastcgi
app written in c++ I needed to handle signals and I didn't see a better
way to cleanup than directly calling the destructor

Jul 23 '05 #8
And this fred looks familiar - I remeber also about providing
input/output for my Fred object. I read it from the same place as you I
think :)

Jul 23 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

67
4190
by: Steven T. Hatton | last post by:
Some people have suggested the desire for code completion and refined edit-time error detection are an indication of incompetence on the part of the programmer who wants such features. ...
24
1766
by: s.subbarayan | last post by:
Dear all, According to standards is this valid: char TmpPtrWriteBuffer; void* PtrWriteBuffer =(void*) TmpPtrWriteBuffer; I had a debate with my colleagues that anything cant be typecasted to...
289
1805
by: napi | last post by:
I think you would agree with me that a C compiler that directly produces Java Byte Code to be run on any JVM is something that is missing to software programmers so far. With such a tool one could...
23
2471
by: Kenneth Osenbroch | last post by:
Hi, I am having trouble translating the following lines of Visual Basic code to C. For iCounter = Len(sReference) To 1 Step -1 iSum = iSum + Val(Mid(sReference, iCounter, 1)) * iMultiplier...
5
4510
by: Sriram Rajagopalan | last post by:
Hi, Is the extra comma at the end of an enumerator-list valid according to the C standards? With the gcc compiler the following is valid: enum DAYS {MONDAY, TUESDAY, }day1; gcc does not...
7
1325
by: jammie_linux | last post by:
Hi, Please look at the following code. In my opinion, the value of "char *str" in the main function should not change even after calling the function "funct" and that's beacuse the "char *str" in...
9
6690
by: shorti | last post by:
db2 V8.2 I have been looking for a good way to log the 'reason code' when we hit an sqlcode that uses them. From what I can tell the reason code is stored in sqlca.sqlerrmc. But, there seems...
21
2799
by: Kannan | last post by:
Its been a while I have done pure C programming (I was coding in C++). Is the following function valid according to standard C? int main(int argc, char *argv) { int x; x = 9; printf("Value...
7
9847
by: Christian Hackl | last post by:
Hi everyone, I've got a question about what makes the "img" element's width/height attributes valid HTML or XHTML. First of all, this is a rather theoretical question, but digging through the...
0
7132
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7009
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7178
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7223
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
7390
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
4602
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3103
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3094
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
302
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.