Back to Blog

LoadRunner VuGen: What’s Up With SPRINTF?

In my custom load testing class, we usually get into specific code examples that demonstrate how to do some tips and tricks in VUGen. One of the things I always like to bring up is the behavior or sprintf. This is a commonly used C function for string manipulation. Many a young LoadRunner lad has come across the dreaded memory violation error in their output log when using sprintf:

Error: C interpreter run time error: Action.c (10): Error — memory violation : Exception ACCESS_VIOLATION received.

Let’s look at why. Here is some code:

----begin code----
int VuserId = 1;
char *GroupName = "Group1";
char TestLoginName[100] = "ScottMoore";
sprintf(TestLoginName, "pTestuser%d%s", VuserId, GroupName);
lr_save_string(TestLoginName, "LoginParam");
lr_output_message("The new variable is called %s", lr_eval_string("{LoginParam}"));
return 0;
----end code----

We’re declaring an integer variable, a character pointer, and a character array. Then we’re using sprintf to put them all together as a new LoadRunner parameter type, and finally sending a message to our output window to tell us the name of the new parameter. Paste this into a script and it will run with no problem.

Now let’s change the line

char TestLoginName[100] = "ScottMoore";


char *TestLoginName = "ScottMoore";

Just for kicks, hit the COMPILE button in VUGen. No errors. We must be in the clear, right? Wrong. Running the script will give you that memory violation error as listed above. Why? The initial space for the ScottMoore\0 that is allocated for the char * is given in CODE area of the executable. The CODE area may not be modified. By changing the variable to a pointer, you’re essentially reserving only 11 bytes (10 characters in the name, plus the 0 terminator). That means there isn’t any room to add the other elements (the VuserID and GroupName). Thus, you get an ACCESS_VIOLATION because sprintf is trying to write to memory it shouldn’t. We could go into a discussion about the fact that there is no such thing as a string in C, but that is a different blog posting. My point is simple: Understanding VUGen means you need to have a good understanding of C and the role VUGen plays as an interpreter/compiler.

I wish to thank Russell Van Steenburgh at the Script Farm, and Mark Sechrest for helping me be able to explain this to mere mortals like myself. 🙂

Back to Blog