Search code examples
c++winapivisual-c++mallocstrdup

How to use Malloc and StrDup together when StrDup is in a while loop?


I have a code here. I am using malloc to allocate memory to my struct. One member of this struct is assigned a string using StrDup inside a while loop though other members dont have to change their values. Now, as I am using StrDup, I have to clean memory otherwise there would be memory leaks but the cleaning of memory corrupts my struct malloc. What should I do? Thanks in Advance.

    do
    {
       if( pURL == NULL )
           break ;
       pData->URL = StrDupA(pURL) ;

    }while(pURL != NULL) ;

Solution

  • Well, the simple answer is that you must free pData->URL before replacing it with the result of StrDupA. Like this:

    pData->URL = NULL ;
    do
    {
        pURL = //Some Function Here
        LocalFree(pData->URL) ;
        pData->URL = StrDupA(pURL) ;
    }while(pURL != NULL) ;
    

    As for the exception that is being raised, you state in a comment that at some point pURL is NULL. When that happens StrDupA will fail. I can't really advise you on how to fix this because I just cannot get my head around what this code is trying to do.

    You are quite possibly also leaking the memory that is created by the function that assigns pURL.

    I can't understand why would want to use StrDupA rather than the strdup that the C runtime provides. You are calling StrDupA from Shlwapi.dll. That makes no sense to me. Call the one from the C runtime and free the memory with good old free().

    I also don't understand why the loop termination is designed to apparently never terminate. And I've not looked at any of your code other than this single do while loop.