🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c++
Article #3941

C++ syntactic trap

#3941
From: Stephen Vavasis
Date: Sat, 06 Apr 1996 19:33
40 lines
2308 bytes
I have just spent a long time tracking down a mysterious bug (the
heap-trashing variety of bug) in my program caused by a syntactic trap
in C++.  The troubling thing about this trap is that none of the unix
compilers I tried (gcc-2.7.2, Sun SC3.0.1, HP-UX cfront 3.0.3) issued
a warning about the mistake, even on the highest warning level.  Only
Visual C++4.0 observed that there might be a problem.  Here is an
example of the trap.  This program asks the user how many asterisks,
and then prints out that many asterisks.

#include <iostream.h>
int main() {
  cout << " How many *'s? ";
  int sz; cin >> sz;
  char* a = new char(sz + 1); // bug is here, but syntax is legal.
  for (int i = 0; i < sz; i++)
    a[i] = '*';
  a[sz] = 0;
  cout << a << endl;
  delete[] a;
  return 0;
}

(Does everyone see the error?  I did not, even after staring at my
code for a long time.  The point is that the marked statement is an
unintended cast from int to char because I used () instead of [].)

I would like to make a plea to the compiler-writers who read this
group: please issue warnings for syntactic trouble spots!  Implicit
type conversion probably creates other traps that I haven't thought
of.  C++ programmers like me need help from the compiler to navigate
the traps!

-- Steve Vavasis (vavasis@cs.cornell.edu)
---
[ comp.std.c++ is moderated.  To submit articles: Try just posting with your 
                newsreader.  If that fails, use mailto:std-c++@ncar.ucar.edu
  comp.std.c++ FAQ: http://reality.sgi.com/austern/std-c++/faq.html
  Moderation policy: http://reality.sgi.com/austern/std-c++/policy.html
  Comments? mailto:std-c++-request@ncar.ucar.edu 
]
Technical Details
Message-ID: <4k3q4p$lkd@syn.cs.cornell.edu>
Path: arc1-ca.pugleaf.net!fido.asd.sgi.com!austern

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!fido.asd.sgi.com!austern
From: vavasis@CS.Cornell.EDU (Stephen Vavasis)
Newsgroups: comp.std.c++
Subject: C++ syntactic trap
Date: 06 Apr 1996 11:33:39 PST
Organization: Cornell Univ. CS Dept, Ithaca NY 14853
Approved: austern@isolde.mti.sgi.com
Message-ID: <4k3q4p$lkd@syn.cs.cornell.edu>
NNTP-Posting-Host: isolde.mti.sgi.com
X-Original-Date: 5 Apr 1996 13:52:09 -0500
X-Auth: PGPMoose V1.1 PGP comp.std.c++
 iQBVAwUBMWbHFEy4NqrwXLNJAQFpQAH+Lo5yP9Gurz7LTLklIIxiMghHtU2JKM18
 M/+dh2agzyzLQQnOzAtH/NRsc3xmUFWdfXSt3SGEp+XNLoLizqBz/g==
 =yNcj
Originator: austern@isolde.mti.sgi.com