malloc,范围,初始化(或缺少)

时间:2011-12-08 18:53:47

标签: visual-studio-2010 scope initialization malloc

以下是代码:

 // allocation  
void allocateSymbolStorage(char **pepperShakerList, char **pepperList)
{   
    //  allocate storage for an array of pointers
    pepperShakerList = (char **) malloc(MAX_PEPPER_SHAKERS * sizeof(char *));

    for (int i = 0; i < MAX_PEPPER_SHAKERS; i++)
    {
        if ((pepperShakerList[i] = (char *) malloc(MAX_SHAKERNAME_LENGTH * sizeof(char))) == NULL)
            fatalError("failed pepperShakerList alloc");
    }

    //  allocate storage for an array of pointers 
    pepperList = (char **) malloc(MAX_PEPPERS * sizeof(char *));

    for (int i = 0; i < MAX_PEPPERS; i++)
    {
        if ((pepperList[i] = (char *) malloc(MAX_PEPPER_LENGTH * sizeof(char))) == NULL)
            fatalError("failed pepperList alloc");
    }
}

void buildPepperShakers(void)
{
    char **pepperShakerList, **pepperList; 

    allocateSymbolStorage(pepperShakerList, pepperList);

    // ....

    freeSymbolStorage(pepperShakerList, pepperList);
}

这是VS 2010错误: :警告C4700:未初始化的局部变量'pepperList'使用

这是混乱: 如果在分配函数中分配char **,为什么会出错?这是不属于范围的问题吗?

2 个答案:

答案 0 :(得分:0)

这就是你想要的,你需要取消引用传入的指针:

*pepperShakerList = (char *) malloc(MAX_PEPPER_SHAKERS * sizeof(char *));

答案 1 :(得分:0)

假设你正在讨论的是pepperList而不是symbolList,并且假设您在allocationSymbolStorage中的代码反映了您想要做的事情,那么VC正在抱怨。

现在你的代码会崩溃,因为在buildPepperShakers()中你没有从allocateSymbolStorage获得任何值。

因此,您的allocateSymbolStorage应声明为:

void allocateSymbolStorage(char ***pepperShakerList, char ***pepperList)

然后将buildPepperShakers中的本地指针持有者变量的地址,即pepperListpepperShakerList传递给分配函数,以便它可以根据TJD的答案进行分配。那就是:

void buildPepperShakers(void) {
       char **pepperShakerList, **pepperList;
       allocateSymbolStorage(&pepperShakerList, &pepperList); 
}

当然,您的allocateSymbolStorage正文现在变为:

void allocateSymbolStorage(char ***pepperShakerList_p, char ***pepperList_p)
{   
    char **pepperShakerList, **pepperList;
    //  allocate storage for an array of pointers
    pepperShakerList = (char **) malloc(MAX_PEPPER_SHAKERS * sizeof(char *));

    for (int i = 0; i < MAX_PEPPER_SHAKERS; i++)
    {
        if ((pepperShakerList[i] = (char *) malloc(MAX_SHAKERNAME_LENGTH * sizeof(char))) == NULL)
            fatalError("failed pepperShakerList alloc");
    }

    //  allocate storage for an array of pointers 
    pepperList = (char **) malloc(MAX_PEPPERS * sizeof(char *));

    for (int i = 0; i < MAX_PEPPERS; i++)
    {
        if ((pepperList[i] = (char *) malloc(MAX_PEPPER_LENGTH * sizeof(char))) == NULL)
            fatalError("failed pepperList alloc");
    }

    *pepperShakerList_p = pepperShakerList;
    *pepperList_p = pepperList;

}

现在VC不应该抱怨。虽然这是对对象进行内存管理的一种丑陋方式:-)