Advertisement

VERY strange string problem...

Started by October 12, 2000 01:56 PM
3 comments, last by Houdini 24 years, 2 months ago
Ok, this one is just confusing the hell outta me. A friend of mine is writing a string class and he sent me his basic working version. He says it compiles and runs fine on his computer (using GCC) but I of course get a compile error compiling under VC++. Here''s function with the error:

String String::operator +(const String & right) const
{
     int len = right.length() + length() + 1;

     char val[len];  // This line compiles fine for him!!!

//other crap goes here
}
 
How the heck can that compile and run for him? The value of len won''t be known till runtime so how can it allocate it on the stack? I figured that perhaps the compiler saw it and just changed it to a "char *var = new char[len];" and allocates it on the heap, but then what would delete the allocation? I guess my question is, HOW does this work, WHERE is the allocation taking place (on the heap or stack) and WHAT is deleting the allocation? - Houdini
- Houdini
I'm no guru of GCC, but it looks to me like that shouldn't compile. I'd make absolutely certain that you're looking at the exact same code your friend is using to compile. You just can't do something like that in C++, for exactly the reasons you state.

You know, it would be interesting if your friend could get you the source-annotated listing for that function, see just exactly what's going on there.

Edited by - Stoffel on October 12, 2000 3:15:42 PM
Advertisement
    String String::operator +(const String & right) const{     int len = right.length() + length() + 1;     char val[len];  // This line compiles fine for him!!!       //other crap goes here}    


This is illegal in C++. HOWEVER, the latest draft/working/whatever version of the C standard allows for this, IIRC.

I generally don''t watch the standards closely, but I think the latest C standard allows for variable-allocated arrays. Maybe gcc follows that and accidentally (purposely) extends it to C++?


---- --- -- -
Blue programmer needs food badly. Blue programmer is about to die!
try val = new char[len]

http://members.xoom.com/myBollux
Would this work if you overload the [] operator and the delete operator?

thx,
Phil

Visit Rarebyte!
and no!, there are NO kangaroos in Austria (I got this questions a few times over in the states ;)
Visit Rarebyte! and no!, there are NO kangaroos in Austria (I got this question a few times over in the states ;) )

This topic is closed to new replies.

Advertisement