Here is my code:
TCHAR *sResult = (TCHAR *) calloc(16384+1, sizeof(TCHAR));
sResult = (TCHAR *) GetValueFromFile(sFilename,L"Dept",L"Names"); // #1
_tcscpy(sResult,(TCHAR *) GetValueFromFile(sFilename,L"Dept",L"Names"); // #2
Function:
TCHAR *GetValueFromFile(TCHAR *sFilename,TCHAR *sDept,TCHAR *sNames)
{
...
}
Which is correct to do? #1 or #2?
Thanks everyone.
Edit #1:
I’m using VS2008 in .cpp files, but really just C code.
I just need to open a file in GetValueFromFile and send the return string back. Should I be allocating memory in GVFF and freeing it in my program?
main()
{
TCHAR *sResult;
DWORD dwRetVal = GetValueFromFile(sFile,L"Dept",L"Name", &sResult);
...
free(sResult);sResult=NULL;
}
Like this?
DWORD GetValueFromFile(TCHAR *sFilename,TCHAR *sDept,TCHAR *sNames, TCHAR ** sValueData)
{
dwL = GetStringDataLength(…)
*sValueData = (TCHAR *) calloc(dwL+1, sizeof(TCHAR));
_tcscpy_s(sValueData,dwL,sDataFromFile);
}
Well, first off, this is unnecessary in case 1 and leads to a problem:
I don’t know where
16384+1is coming from, so I’ll assume that’s “correct” for now, but you proceed to set the pointer to another value in the very next line. That, my friend, is a memory leak. Why are you allocating memory that you don’t need?Your question really boils down to the implementation of
GetValueFromFile. If that function returns a pointer (which it does) then it should certainly be a valid pointer and you are responsible for deallocating it (probably. Again, depends on the implementation).There is no need to create a copy unless you actually need a copy. There is no “right” or “wrong” here from the information you have given us, we need to know the details of
GetValueFromFile.Per your edit:
That function does not return anything. At all. It’s signature says it returns a DWORD, not a
TCHAR*. It is obviously different than your first example as it initializes the pointer as an output argument (the 4th one), but that is not how you are calling it in your original example.I am just further confused now, but if the function initializes the pointer then you need only declare (no memory allocation outside of the function) the pointer and pas in its address.
Given
Then the proper way to pass your pointer in is:
The function initializes your
resultvariable to point to a valid location. Do not forget that you are now responsible for deallocating it!