Why is malloc overwriting the contents of my variable?

Posted on 2007-03-26
Last Modified: 2010-05-18
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);
            if(!szPwd) {
                  puts("Could not allocate buffer for pwd");
            if(!GetCurrentDirectory(size+1,szPwd)) {
                  printf("Could not get size: Error:%d\n",GetLastError());
            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");
            printf("JobID is %s\n",jobID);
Question by:TristinColby
  • 2
LVL 53

Expert Comment

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

make that :

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

Accepted Solution

Infinity08 earned 500 total points
ID: 18796279
Same here :

            char *szPwd = (char *)malloc((sizeof(char)size)+1);

becomes :

            char *szPwd = (char *)malloc(size+1);

and here :


becomes :


Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode ( They will have you believe that Unicode requires you to use…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now