0

I'm trying to generate a GUID in a platform agnostic manner, most search results suggest using BOOST or platform specific libraries. I remember once coming across the following snippet and I was wondering if this is a reliable way of generating GUID's:

unsigned int generateGuid()
{
    char c;
    return (unsigned int)&c;
}

More specifically, does this guarantee a unique value always? And if not, what are some good lightweight and cross-platform approaches of doing this?

PhilipMR
  • 49
  • 1
  • 4
  • 7
    That's an absolutely **awful** way of generating a GUID. And in fact a GUID is **never** going to fit in an `unsigned int`. – Mark Ransom Dec 15 '16 at 23:33
  • 2
    No, this does not guarantee a unique value. Call it multiple times in a simple loop, for example, and there is a fair chance it will return the same value every time. – Peter Dec 15 '16 at 23:33
  • If you don't like boost, use [ossp uuid library](http://www.ossp.org/pkg/lib/uuid). – mvp Dec 15 '16 at 23:35
  • Windows: https://msdn.microsoft.com/en-us/library/ms688568%28VS.85%29.aspx?f=255&MSPPError=-2147217396 -- Linux: https://linux.die.net/man/3/libuuid – kayleeFrye_onDeck Dec 16 '16 at 00:52

2 Answers2

1
A basic example:

#include <boost/uuid/uuid.hpp>            // uuid class
#include <boost/uuid/uuid_generators.hpp> // generators
#include <boost/uuid/uuid_io.hpp>         // streaming operators etc.

int main() {
    boost::uuids::uuid uuid = boost::uuids::random_generator()();
    std::cout << uuid << std::endl;
}
Example output:
BufBills
  • 8,005
  • 12
  • 48
  • 90
0

No it is not. This function will return some address from stack depending on where it is called. In two subsequent calls or tight loop it will be always the same address. For example in Visual Studio the default stack size is 1 MB, I think, so in the best case you will get one million unique values. Typical program does not use more than 1KB of stack so in that case you will get at most one thousand unique values.

Mateusz Drost
  • 1,171
  • 10
  • 23