Sprintf fails with invalid parameter passed to function in loadrunner while defining string using *varname

1.6k Views Asked by At

First version: (Works)

//Using sprintf
int index = 56;
char filename[64], * suffix = "txt";
sprintf(filename, "log_%d.%s", index, suffix);
lr_output_message ("The new file name is %s", filename);
//This works

Second version: (Does not work)

 //Using sprintf 
int index = 56;
char *filename, * suffix = "txt";
sprintf(filename, "log_%d.%s", index, suffix);
lr_output_message ("The new file name is %s", filename);
//Fails with invalid parameter passed to function
2

There are 2 best solutions below

6
On

In the second case you have to allocate space in memory for filename, using malloc()

char *filename = malloc(64);

If you do not allocate space you will have undefined behaviour because of you are writing to a not initialized pointer.

Remember to always check the return of malloc:

if (filename != NULL)
{
   // your code ...
}
else
{
   printf("No space available for filename");
}

Once you allocate memory and the usage is done. you've to release the allocated memory using free()

2
On
  • Your first version (is correct and) works, because there is (enough) memory allocated for filename, which is a char array.

    char filename[64]. //....
    
  • Your second version (is incorrect and) does not work, because there is no memory allocation for filename, which you define as a pointer.

    char *filename,//...
    

This does not allocate memory to the pointer automatically.

In other words, the pointer is not pointing to any valid memory address. So, trying to access the memory pointed by the pointer is invalid and invokes undefined behaviour.

Solution: You need to allocate memory to the pointer before you use it. You can use malloc() and family functions to allocate memory to the pointer.

Also, one you allocate memory and the usage is done. you've to release the allocated memory using free()