cppython
cppython

Reputation: 1279

c++ weird string size

I encountered a weird string size problem. Here is my sample code

sampleA

std::string getexepath()
{
    char result[ PATH_MAX ];
    int found;
    ssize_t count = readlink( "/proc/self/exe", result, PATH_MAX );
    found = std::string(result).find_last_of("/");
    std::string pp = std::string(result).substr(found+1);
    std::string kk = std::string(result).substr(found+1);
    std::cout << kk << kk.size() << std::endl;
    return kk;
}

sampleB

std::string getexepath()
{
    char result[ PATH_MAX ];
    int found;
    ssize_t count = readlink( "/proc/self/exe", result, PATH_MAX );
    found = std::string(result).find_last_of("/");
    //std::string pp = std::string(result).substr(found+1);
    std::string kk = std::string(result).substr(found+1);
    std::cout << kk << kk.size() << std::endl;
    return kk;
}

The outputs are different; the sampleB output is 2 char more than sampleA. I guess the difference is '\0'; sampleB output is including '\0' and sampleA isn't.

I am wondering what causes the problem. after review the answer, now I know i missed '\0'. but i still want to know why added this statement "std::string pp = std::string(result).substr(found+1)" will cause a difference result.

Thanks

Upvotes: 0

Views: 259

Answers (2)

kevinX
kevinX

Reputation: 11

The memory of result[ PATH_MAX ] on the stack is not initialized, so the content of result is uncertained. Like the comment of WhozCraig:

readlink() does not append a null byte to buf.

So the '\0' may appear in every place after result[ count-1 ], and the output in your code is undefined. When declare a C format string, we'd better initialize the string like this: char result[ PATH_MAX ] = {0};. Hope these can help you.

Upvotes: 1

CS Pei
CS Pei

Reputation: 11047

You guess is right. The problem is that you forgot to set result[count]=0 . Therefore your code has undefined behavior because the char array result is not terminated by '\0'.

After you add

    result[count] = 0;

before found = ..., you will get the same results for both sample A and sample B.

Upvotes: 2

Related Questions