Increasing memory allocation in function
Hello everyone, I am trying to get a function to increase memory allocation for a LPSTR(char *) in a function. Basically I am aiming for a string concatenation function which includes the calloc/free - reducing the amount of code in my program.
However, my function is not working as I intended. At first I wrote a variant(LPSTRAddToOriginal or variant 0) that I hoped would take an LPSTR and increase memory allocation in the function and do the strcat:ing there. That function makes the strcat alright but when the execution returns to the main(), the LPSTR is back to its original state. Also, calling it several times without freeing the original LPSTR leaks memory.
My second attempt(LPSTRAddToOriginal2 or variant 1) returns a LPSTR and this actually works but with again, calling it several times without freeing the original LPSTR leaks memory.
There is something I am missing here, should it not be possible to do this?
Thankful for any advice!
/Anders
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <windows.h>
int LPSTRAddToOriginal(LPSTR lpzOriginalString, LPSTR lpzStringToAdd)
{
LPSTR lpzTemp;
lpzTemp = (char *)calloc(strlen(lpzOriginalString) + strlen(lpzStringToAdd) + 1,sizeof(char));
strcpy(lpzTemp, lpzOriginalString);
strcat(lpzTemp, lpzStringToAdd);
free(lpzOriginalString);
lpzOriginalString = (char *)calloc(strlen(lpzTemp) + 1, sizeof(char));
strcpy(lpzOriginalString, lpzTemp);
printf("lpzTemp: %s\n", lpzTemp);
free(lpzTemp);
return 0;
}
LPSTR LPSTRAddToOriginal2(LPSTR lpzOriginalString, LPSTR lpzStringToAdd)
{
LPSTR lpzTemp;
lpzTemp = (char *)calloc(strlen(lpzOriginalString) + strlen(lpzStringToAdd) + 1,sizeof(char));
strcpy(lpzTemp, lpzOriginalString);
strcat(lpzTemp, lpzStringToAdd);
free(lpzOriginalString);
lpzOriginalString = (char *)calloc(strlen(lpzTemp) + 1, sizeof(char));
strcpy(lpzOriginalString, lpzTemp);
printf("lpzTemp: %s\n", lpzTemp);
free(lpzTemp);
return lpzOriginalString;
}
int main(int argc, char *argv[]) {
LPSTR lpzFirst;
LPSTR lpzSecond;
LPSTR lpzSpace;
int iResult;
int iCtrl;
int iVariant;
if (argc>1)
{
iVariant=1;
}
else
{
iVariant=0;
}
lpzSecond="Second";
lpzSpace="-";
lpzFirst ="First";
// Test loop
for (iCtrl=1;iCtrl<10;iCtrl++)
{
if (iVariant==0)
{
// variant 0 - Does not work and leaks memory
iResult = LPSTRAddToOriginal(lpzFirst, lpzSpace);
iResult = LPSTRAddToOriginal(lpzFirst,lpzSecond);
}
else
{
// variant 1 - Works but leaks memory
lpzFirst="First";
lpzFirst=LPSTRAddToOriginal2(lpzFirst, lpzSpace);
lpzFirst=LPSTRAddToOriginal2(lpzFirst, lpzSecond);
}
printf("%i lpzFirst: %s\n",iVariant, lpzFirst);
}
return 0;
}