Jump to content
  • Advertisement
Sign in to follow this  


This topic is 4527 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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);
    v = makevec(makevec(0.0f, 1.0f, 2.0f)[2], 0.0f, 1.0f);
    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?

Share this post

Link to post
Share on other sites
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.

Share this post

Link to post
Share on other sites
Undefined behaviour can do anything, including "appear to work correctly".

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

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!