2

This is the code I have in my main C function.

char *filename;            

filename = malloc(2001); //if I don't do this step it gives me an error

filename = ListDirectoryContents("test_data\\tmp");//this returns a string  for filename

printf("filename : %s ", filename);//value of filename is displayed which is an address and is NOT NULL OR EMPTY

copyObjectFileInINfolder(filename, logger);//here I am passing the filename to this function where I am getting the error

Ok now what I am trying to do is I am trying to pass the string filename into the function (in the function the variable for filename is object)

void copyObjectFileInINfolder(char *object, char* logger2);
{
        char source[500];
        char destination[500];
        char cmd[1000];
        printf("\nobject : 123%s123\n", object);//Here the out put I see is "object : 123123"
        printf("\nlogger : %s\n", logger2);

         if(flag ==2)//for windows
         {      
                  //object +=14;
                  printf("\nobject : %s\n", object););//Here the out put I see is "object : "

                  sprintf(source, "test_data\\tmp\\%s", object ); //full address of source file
                  sprintf(destination, "..\\in\\%s", object ); //full address of where the file is to be copied


                  sprintf(cmd,"IF EXIST %s del /Q %s", destination, destination);//to make sure to delete the file if it already exists in the safeXhonw\in folder
                  system(cmd);
                  memset(cmd,0,strlen(cmd));//deleting old values stored in cmd

                  sprintf(cmd, "copy %s %s", source, destination );
         }

        system(cmd);//using linux terminal or Windows command prompt to copy file from source folder into safeXhomedirectory in folder             

        memset(cmd,0,strlen(cmd));//deleting old values stored in cmd

        memset(source,0,strlen(source));//deleting old values stored in source
        memset(destination,0,strlen(destination));//deleting old values stored in destination

}

But when I pass it, it is always empty, i.e. filename/object does not show any value, not even " (null)". I know it might be something to do with this malloc command.

HERE IS the other function

char* ListDirectoryContents(const char *sDir)
{
WIN32_FIND_DATA fdFile;
HANDLE hFind = NULL;

char sPath[2000];

//Specify a file mask. *.* = We want everything!
sprintf(sPath, "%s\\*.*", sDir);

if((hFind = FindFirstFile(sPath, &fdFile)) == INVALID_HANDLE_VALUE)
{
    printf("Path not found: [%s]\n", sDir);
    return 1;
}

do
{
    //Find first file will always return "."
    //    and ".." as the first two directories.
    if(strcmp(fdFile.cFileName, ".") != 0
            && strcmp(fdFile.cFileName, "..") != 0)
    {
        //Build up our file path using the passed in
        //  [sDir] and the file/foldername we just found:
        sprintf(sPath, "%s\\%s", sDir, fdFile.cFileName);

        //Is the entity a File or Folder?
        if(fdFile.dwFileAttributes &FILE_ATTRIBUTE_DIRECTORY)
        {
            printf("Directory: %s\n", sPath);
            ListDirectoryContents(sPath); //Recursion, I love it!
        }
        else{
            printf("File: %s\n", sPath);
            FindClose(hFind);
            return sPath;
        }
    }
   }while(FindNextFile(hFind, &fdFile)); //Find the next file.

FindClose(hFind); //Always, Always, clean things up!

    return "";
}
10
  • 3
    I'm almost sure you're overwriting the malloc()-ed memory. Commented Nov 12, 2015 at 12:17
  • @SouravGhosh how to solve this? Commented Nov 12, 2015 at 12:18
  • 3
    Show us ListDirectoryContents(). Commented Nov 12, 2015 at 12:18
  • 4
    filename = malloc(2001); filename = ListDirectoryContents("test_data\\tmp"); makes no sense. Malloc is useless here. If it gives you error when you remove the first line, then you have undefined behavior somewhere. Commented Nov 12, 2015 at 12:19
  • 1
    Yup - what you are doing is inherently borken. Commented Nov 12, 2015 at 12:24

1 Answer 1

4

You have two problems: The first is pretty obvious, and that's the reassignment of filename making you lose the original pointer.

The other problem is that in the ListDirectoryContents function you return a pointer to the local variable sPath, which will lead to undefined behavior because once the function returns the variable doesn't exist any more.

I can see two possible solutions:

  1. Pass the filename as a second argument to the ListDirectoryContents function, and use that argument instead of sPath.
  2. Don't allocate memory for filename, instead allocate sPath dynamically in the ListDirectoryContents function.

Also, no matter what you do to your problems, the common thing to do when a function fails somehow is not to return a pointer to a valid, but empty, string. Instead one usually returns NULL.

Oh by the way, the recursion in ListDirectoryContents won't really work as you expect, as you don't handle the returned value, you just discard it.

Sign up to request clarification or add additional context in comments.

2 Comments

I would go with (2), on the grounds that the caller has no idea how much space is needed, (that, and comment/doc to emphasize that the caller assumes responsibility for result lifetime).
In fact, this almost demands returning some more complex 'list' struct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.