Question

I posted a problem and got an answer here. Here is the code which i debugged on VC2010. I get the run time error shown at the end. What is wrong with usage of sdir?

#include<iostream>
#include<stdlib.h>

#include<windows.h>
void make_dir(int depth, char *dir) {
  if (depth < 3) {

    CreateDirectoryA (dir,NULL); 

    for (int i = 0; i < 10; i++) {
       char *sdir= (char*)malloc(strlen(dir+10)); // XXX 10?
        strcpy(sdir, dir);
        sprintf(sdir + strlen(sdir), "\\%d", i); 
        printf("%s\n", sdir);
        CreateDirectoryA(sdir,NULL);
        make_dir(depth + 1, sdir);
        free(sdir);
    }   
  }     
}

int  main()
{
    make_dir(0,"dir");
    return 1;
}

The error is:

HEAP[mkdir.exe]: Heap block at 004114E8 modified at 00411514 past requested size of 24 Windows has triggered a breakpoint in mkdir.exe.

This may be due to a corruption of the heap, which indicates a bug in mkdir.exe or any of the DLLs it has loaded.

This may also be due to the user pressing F12 while mkdir.exe has focus.

The output window may have more diagnostic information. The program '[3008] mkdir.exe: Native' has exited with code 0 (0x0).

Was it helpful?

Solution

The most glaring error I see is that you're adding 10 to the pointer being passed to strlen; this will either read memory outside of the string if the string is less than 10 characters long, or subtract 10 from the length of the string otherwise. You probably want to be adding 10 to the result of strlen, not the input.

In other words, move the ) after the +10 to before the +10.

OTHER TIPS

This line:

char *sdir= (char*)malloc(strlen(dir+10));

This takes the string dir and offsets it ten characters before getting the length. Are you sure you don't mean:

char *sdir= (char*)malloc(strlen(dir)+10);

Also, are you sure there is room for the terminating '\0' character as well?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top