在多个“\0”处拆分 char*字符

发布于 2024-11-15 03:28:08 字数 1351 浏览 3 评论 0原文

以下是 C++ 语言。 我有一个包含环境变量的字符串,我需要在每个变量的声明处将其拆分将其存储在字符串中:

char* envVars = "=::=::\0system=blah\0othervar=blah\0"

因此,我使用 cstring 函数在出现空终止符 char '\0' 时分割字符串,但它只是进入无限循环。为什么?

找到解决方案:查看代码注释:

vector <string> GetEvironmentVariables()
{
   vector <string> envVariables;
   char* environVar = GetEnvironmentStrings();
   char* pos        = strchr( environVar, '\0' );

   // As far as I know environVar =::=::\0environVar1=...\0environVar2=...\0" 
   // so the string has many NULL terminators  

   while ( pos != NULL )
   {
       char* buffer;
       strncpy( buffer, environVar, strlen(pos) );   // on the 1st iteration: buffer SHOULD = "=::=::\0", 2nd buffer SHOULD = "environVar=...\0"
       envVariables.push_back( string(buffer) );
       environVar = pos;                            // SOLUTUION: I need to move over the '\0' pos points to so: environVar = ++pos;
       pos        = strchr( environVar, '\0' );

       printf("Var: %s \n", envVariables.back().c_str() ); 
       printf("env: %s \n", environVar);
       system("PAUSE");
       // prints out this:
       // Var: cRek (same junk each iteration)
       // env: 
       // Press any key to continue....
   }

   FreeEnvironmentStrings( environVar ); 
   return envVariables;       
}

The following is in C++.
I have a string that contains the environment variables I need to split it at the declaration of each variable & store it in a string:

char* envVars = "=::=::\0system=blah\0othervar=blah\0"

So I am using cstring functions to split the string at the occurence of the null terminator char '\0' but it's just going into an infinite loop. Why?

SOLUTION Found: look at code comments:

vector <string> GetEvironmentVariables()
{
   vector <string> envVariables;
   char* environVar = GetEnvironmentStrings();
   char* pos        = strchr( environVar, '\0' );

   // As far as I know environVar =::=::\0environVar1=...\0environVar2=...\0" 
   // so the string has many NULL terminators  

   while ( pos != NULL )
   {
       char* buffer;
       strncpy( buffer, environVar, strlen(pos) );   // on the 1st iteration: buffer SHOULD = "=::=::\0", 2nd buffer SHOULD = "environVar=...\0"
       envVariables.push_back( string(buffer) );
       environVar = pos;                            // SOLUTUION: I need to move over the '\0' pos points to so: environVar = ++pos;
       pos        = strchr( environVar, '\0' );

       printf("Var: %s \n", envVariables.back().c_str() ); 
       printf("env: %s \n", environVar);
       system("PAUSE");
       // prints out this:
       // Var: cRek (same junk each iteration)
       // env: 
       // Press any key to continue....
   }

   FreeEnvironmentStrings( environVar ); 
   return envVariables;       
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

夏至、离别 2024-11-22 03:28:08

您可以更简单地执行此操作,而无需依赖 C 标准库函数:

#include <string>
#include <vector>

int main()
{
    const char* environment = "x=x\0y=y\0z=z\0";

    std::vector<std::string> environment_strings;
    const char* current_string = environment;

    while (*current_string)
    {
        environment_strings.push_back(current_string);
        current_string += environment_strings.back().length() + 1;
    }
}

此处使用的 std::string 构造函数从指向的数组中获取字符,直到到达 \0。然后我们移动到下一个字符串,该字符串从前一个字符串末尾后面的一个字符开始。当到达“空”字符串(结束序列的双空终止符)时,它会停止。

You can do this a bit more simply and without relying on the C Standard Library functions:

#include <string>
#include <vector>

int main()
{
    const char* environment = "x=x\0y=y\0z=z\0";

    std::vector<std::string> environment_strings;
    const char* current_string = environment;

    while (*current_string)
    {
        environment_strings.push_back(current_string);
        current_string += environment_strings.back().length() + 1;
    }
}

The std::string constructor used here takes characters from the pointed-to array until it reaches a \0. We then move to the next string, which begins one character past the end of the previous string. It stops when it reaches an "empty" string (the double null terminator that ends the sequence).

稍尽春風 2024-11-22 03:28:08

我本以为它会立即退出,但实际上手册页显示:

终止空字符被视为字符串的一部分;因此,如果c'\0',函数将定位终止'\0'

当然,pos = strchr(environVar, '\0');的结果是*pos == '\0'strlen(pos) == 0 。所以你总是复制零个字符。没用。

您还可以设置 environVar = pos;,而不跳过 NUL 字符。因此,下一次调用 strchr 返回 environVar 并且不再取得任何进展。


您还忘记初始化缓冲区,您将一个野指针传递给strncpy,这将破坏内存的随机部分。此错误一旦你修正了长度参数始终为零的事实,它可能会抬起它丑陋的头。

I would have expected this to exit immediately, but actually the man page says:

The terminating null character is considered to be part of the string; therefore if c is '\0', the functions locate the terminating '\0'.

Of course, the result of pos = strchr(environVar, '\0'); is that *pos == '\0' and strlen(pos) == 0. So you always copy exactly zero characters. Not useful.

You also set environVar = pos;, without skipping over the NUL character. So the next call to strchr returns environVar and no more progress is ever made.


You've also forgotten to initialize buffer, you're passing a wild pointer to strncpy which will corrupt a random part of memory. This bug will probably rear its ugly head as soon as you fix the fact that the length parameter is always zero.

叫思念不要吵 2024-11-22 03:28:08

这条线是错误的。

strncpy( buffer, environVar, strlen(pos) );

pos 位于第一个空值处,长度为零。您可能需要 strlen(environVar)。

这行代码可能会导致无限循环:

environVar = pos;

由于 pos 位于 \0,因此它将返回相同的指针。尝试 pos + 1。

This line is wrong.

strncpy( buffer, environVar, strlen(pos) );

pos is positioned at the first null, and has a length of zero. You probably want strlen(environVar).

This line is probably causing the infinite loop:

environVar = pos;

Since pos is positioned at \0, it is going to return that same pointer. Try pos + 1.

孤千羽 2024-11-22 03:28:08
#include <cstring>
#include <string>
#include <vector>

using namespace std;

int main ()
{
    vector<string> res;

    const char *s = "=::=::\0system=blah\0othervar=blah\0";
    const char *p = s;

    while (*s != '\0')
    {
        p = strchr (p, '\0');
        res.push_back (s);
        s = ++p;
    }
}
#include <cstring>
#include <string>
#include <vector>

using namespace std;

int main ()
{
    vector<string> res;

    const char *s = "=::=::\0system=blah\0othervar=blah\0";
    const char *p = s;

    while (*s != '\0')
    {
        p = strchr (p, '\0');
        res.push_back (s);
        s = ++p;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文