0

代码看起来像:

char *global1 = NULL;
char *global2 = NULL;
char *global3 = NULL;
char *global4 = NULL;

void func2(char *gPtr, char **gPtrToInitialize)
{
    if(*gPtrToInitialize == NULL)                     // Here, gPtr is correct
    {
        *gPtrToInitialize = dlcalloc(MAX_PATH, 1);      
    }                              // Here, gPtr has trailing junk characters

    // Do some initialization
}

void func1()
{
    if(global1 == NULL)
    {
        global1 = dlcalloc(MAX_PATH, 1);
    }
    func2(global1, &global2);
    func2(global1, &global3);
    func2(global1, &global4);

    // Do other tasks

    // Free all allocated global variables
}

注意: 上述代码中,dlcalloc指的是Doug Lea 的malloc.c中定义的代码。


calloc里面之前func2()

gPtr= "C:\Program Files\Test\Path.txt"

calloc进去之后func2()

gPtr= "C:\Program Files\Test\Path.txt♂"


我的问题是,连续dlcalloc()调用是否有可能破坏其他变量的内存?上面的代码是我正在研究的大型代码库的一部分的概括。

4

2 回答 2

1

好的,我刚刚解决了我的问题。这就是发生的事情func2()

  • gPtr指向0x009b0038.
  • strlen("C:\Program Files\Test\Path.txt")= 30 字节。
  • *gPtrToInitializeon allocation 指向的分配正好在's 部分结束后0x009b0057开始。gPtr
  • 由于 指向的字符串gPtr没有尾随的 '\0',因此任何对字符串的操作gPtr实际上也进入了*gPtrToInitialize' 的内存。

当我简单地添加一个尾随'\0'.

感谢您的所有回答!

于 2013-02-26T05:49:39.267 回答
0

dlcalloc shouldn't have any chance of corrupting any other part of memory unless there is a bug in it (which is unlikely). It should either work or fail but shouldn't corrupt anything.

I think that you should look at your use of pointers because in your code above you are passing the address of global2, global3 and global4 to func2. These addresses should never be null and so the call to dlcalloc in func2 should never happen.

I suspect that func2 should look like:

void func2(char *gPtr, char **gPtrToInitialize)
{
    if(*gPtrToInitialize == NULL)                     // Here, gPtr is correct
    {
        *gPtrToInitialize = dlcalloc(MAX_PATH, 1);      
    }                              // Here, gPtr has trailing junk characters

    // Do some initialization
}

I would look elsewhere in your code for similar pointer errors which are much more likely to cause memory corruption.

C pointers are dangerous.

于 2013-02-26T05:09:13.820 回答