I am getting an access violation. Can anyone see why this might occur
in the following code fragment from a GUID generator?

// here is a code fragment fro a GUID creation routine.
// it is crashing with an Access violation

#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

using namespace std;

char* guidStr = "{00000000-0000-0000-0000-000000000000}";


void GenerateGuid()
{
char *pGuidStr = guidStr;
int i;

srand(static_cast<unsigned int> (time(NULL))); /*Randomize based on time.*/

/*Data1 - 8 characters.*/
system("PAUSE");	// code gets to here okay

*pGuidStr++ = '{'; // <code crashes here

// Code Crashes when it trys to access guidStr before it gets to here.
// Unhandled exception at 0x00411486 in XorCryt.exe: 0xC0000005: Access violation writing location 0x0041573c.

system("PAUSE");
}

Thanks in advance for any help.

Recommended Answers

All 3 Replies

Well, the compiler should have complained that you were assigning a string constant to a non-const pointer (char* guidStr). The initialization should have been like this: char guidStr[] = {'{','0','0','0','0','0','0','0','0','-','0','0','0','0','-','0','0','0','0','-','0','0','0','0','-','0','0','0','0','0','0','0','0','0','0','0','0','}',0};

Well, the compiler should have complained that you were assigning a string constant to a non-const pointer (char* guidStr). The initialization should have been like this: char guidStr[] = {'{','0','0','0','0','0','0','0','0','-','0','0','0','0','-','0','0','0','0','-','0','0','0','0','-','0','0','0','0','0','0','0','0','0','0','0','0','}',0};

Thank You so much rubberman! You are absolutely correct - that did the trick!
This is solved!

I think you can also do this these days:

char guidStr[] = "{00000000-0000-0000-0000-000000000000}";

and it will have the same results, but is easier to read! Old compilers would not do that, but current ones, for probably the past 20 years... :-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.