Link to home
Start Free TrialLog in
Avatar of TristinColby
TristinColby

asked on

Why is malloc overwriting the contents of my variable?

Can anyone see why my *jobID is being overwritten???

              char *jobID =      "123456789";
                         DWORD size = GetCurrentDirectory(0,NULL); /*  size == size needed for array - 1 */
            char *szPwd = (char *)malloc((sizeof(char)size)+1);
            memset(szPwd,'\0',sizeof(char)size+1);
            if(!szPwd) {
                  puts("Could not allocate buffer for pwd");
            }
            if(!GetCurrentDirectory(size+1,szPwd)) {
                  printf("Could not get size: Error:%d\n",GetLastError());
                  return(EXIT_FAILURE);
            }
            char *szDir = (char *)malloc(sizeof(char)size+10);  /* PROBLEM HERE */
            /* The statement above is what overwrites the contents of *jobID with what looks like part of a path */
            
            if(!szDir) {
                  puts("Could not allocate Memory for directory name");
            }
            memset(szDir,'\0',sizeof(char)(size+10));
            
            printf("JobID is %s\n",jobID);
            sprintf(szDir,"%s\\%s",szPwd,jobID);
            printf("%s",szDir);
Avatar of Infinity08
Infinity08
Flag of Belgium image

     char *szDir = (char *)malloc(sizeof(char)size+10);  /* PROBLEM HERE */

make that :

      char *szDir = (char *)malloc(size+10);  /* PROBLEM HERE */
ASKER CERTIFIED SOLUTION
Avatar of Infinity08
Infinity08
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial