每当我尝试执行字符串复制时都会出现分段错误。 但是当我直接分配时,相同的代码将起作用。在if语句中,我正在执行strcpy操作,导致内存损坏问题。帮助我理解" strcpy"具有相应代码的功能。
int getEnvVariable()
{
char mPath[20];
char mHome[20];
char *AddressHolder[2];
char *VariableName[2];
VariableName[0]="PATH";
VariableName[1]="HOME";
memset(&mPath,sizeof(mPath),0);
memset(&mHome,sizeof(mHome),0);
AddressHolder[0]=reinterpret_cast<char*>(&mPath);
AddressHolder[1]=reinterpret_cast<char*>(&mHome);
char** namePtr = VariableName;
char** vrbPtr = AddressHolder;
char* tmp;
while(*namePtr != NULL)
{
tmp = getenv(*namePtr);
cout<<"\n tmp - "<<tmp<<"\n";
if(tmp)
{
strcpy(*vrbPtr,tmp);
//*vrbPtr=tmp;
cout<<"\n"<<*namePtr<<": "<<*vrbPtr;
++namePtr;
++vrbPtr;
}
else
{
cout<<"\n Error: Environment veribale name are not set\n";
return -1;
}
}
cout<<"\n"<<VariableName[0]<<" : "<<mPath;
cout<<"\n"<<VariableName[1]<<" : "<<mHome;
return 0;
}
答案 0 :(得分:0)
在strcpy中,* vrbPtr指向AddressHolder的地址。您想指向AddressHolder [0]