scope

Started by
1 comment, last by Zahlman 17 years, 10 months ago
Hey, I've got a quick question. Instead of using structs to represent vectors, I tried out using pointers to floats, like: typedef float *Vector; Now I was doing a little experiment with this stuff, so I wrote this:

#include <iostream>
#include <conio.h>

#define P(t) std::cout << t
#define I(v) std::cin >> v

typedef float* Vector;

Vector makevec(float x, float y, float z)
{
    float vals[] = {x, y, z};
    return vals;
};
int main()
{
    Vector v = makevec(1.0f, 1.0f, 2.0f);
    P(v[2]);
    
    v = makevec(makevec(0.0f, 1.0f, 2.0f)[2], 0.0f, 1.0f);
    P(v[0]);
    
    getch();
    return 0;
}

For some strange reason, this code works and says "22", although I get a warning that I am returning an address to a local variable. The function makevec creates a pointer to three floats on its portion of the stack, then returns the pointer. After the function returns, shouldn't the vals[] variable get popped off the stack, turning the returned pointer invalid and crashing the program?
Advertisement
I'm glad to hear that you know that what you did should cause serious problems [grin]

In C++, the runtime stack (and pointers in general) are very loosely managed. So although the compiler will give you a warning that you're probably pointing at invalid memory, at runtime you get no such warning. The address pointed to by your pointer is still safely within the program's memory addressing space, so you can do whatever you want with it. Just be warned that ex-stack memory is liable to be overwritten without notice.

So, while you say it should "turn your pointer invalid", it's rather turning the memory at which the pointer points invalid.

Long story short, listen to your compiler and stop doing silly things [lol] Use a vector<float> or something along those lines.
Undefined behaviour can do anything, including "appear to work correctly".

And please don't use those god-awful defines.

This topic is closed to new replies.

Advertisement