开发者

C++ using strcpy_s() on a Pointer to char array Pointer

I am to the point I am confusing myself but here is what I have. I have only recently started to familiarize myself with pointers more to a point I feel more comfortable using them, but I am getting an error about the buffer in strcpy_s() being too small.

Please no comments about me using char arrays instead of std::string, its for the HL2SDK which centers around char arrays (no idea why) so I just stick to the pattern.

void func_a()
{
    char *szUserID = new char[64];
    char *szInviterID = new char[64];
    char *szGroupID = new char[64];
    sprintf(szUserID, "%I64d", GetCommunityID(szUserSteamID));
    sprintf(szInvit开发者_开发百科erID, "%I64d", GetCommunityID(g_CvarSteamID.GetString()));
    GetGroupCommunityID(1254745, &szGroupID); // Group Steam Community ID
}

void GetGroupCommunityID(int groupID, char **communityID)
{
    int staticID = 1035827914;
    int newGroupID = 29521408 + groupID;

    char *buffer = new char[64];
    snprintf(buffer, sizeof(buffer), "%d%d", staticID, newGroupID);
    strcpy_s(*communityID, sizeof(*communityID), buffer);

    delete buffer;
}


The problem is you are using sizeof which is a compile time construct to determine the runtime length of *communityID. This will essentially resolve down to sizeof(char*). What you want though is the number of bytes / chars available in *communityID. This information needs to be passed along with the value

GetGroupCommunityID(1254745, &szGroupID, sizeof(szGroupID));

void GetGroupCommunityID(int groupId, char** communityID, size_t length) {
  ...
  strcpy_s(*communityID, length, buffer);
} 

Also in this example a double pointer is unnecessary because you're not changing the pointer, just it's contents. A single pointer will do just fine for that

GetGroupCommunityID(1254745, szGroupID, sizeof(szGroupID));

void GetGroupCommunityID(int groupId, char* communityID, size_t length) {
  ...
  strcpy_s(communityID, length, buffer);
}


If you are using constants values (char *szGroupID = new char[64]) why not declare a constant with the value 64 and use this value; by the way sizeof(szGroupID) is going to return 4 bytes too in a 32 bits compiler.


The second parameter to strcpy_s is the actual size (number of characters) of the buffer pointed to by the first parameter. sizeof(*communityID) only gives you the size of a char * pointer, typically 4 bytes on a 32-bit system. You need to pass in the actual size of *communityID to the GetGroupCommunityID function and pass this on to strcpy_s.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜