Search code examples
c++stringpointersundefined-behaviorstrlen

Why this running code don't print the last value of the string which is /?


I am using a PATH named ncdir (an extern char pointer) used into others file to read netcdf file.

string temp = "/mnt/BIOPHY-RO/Model_AIFS/AIFS_LFN/";
ncdir = (char*) calloc (temp.length(),sizeof(char));
strcpy (ncdir, temp.c_str());
cout<<"last element of the string: "<<ncdir[sizeof(ncdir)]<<endl;

I expect the output P instead of N (Last char in the literal string)


Solution

  • For starters you forgot to reserve memory for the terminating zero

    cdir = (char*) calloc (temp.length(),sizeof(char));
    

    And secondly the expression sizeof(ncdir) gives the size of the pointer ncdir not the size of the pointed array.

    Take into account that the last symbol of the string literal is '/' bur not 'N'.

    Note: If actually it is a C++ code then instead of the standard C function calloc use the operator new to allocate memory.

    Here is a demonstrative program

    #include <iostream>
    #include <string>
    #include <cstring>
    
    int main()
    {
        std::string temp = "/mnt/BIOPHY-RO/Model_AIFS/AIFS_LFN/";
    
        char *ncdir = new char[temp.size() + 1];
    
        std::strcpy ( ncdir, temp.c_str() );
    
        std::cout << "last element of the string: " << ncdir[std::strlen( ncdir ) -1] << std::endl;
    
        delete [] ncdir;
    }
    

    Its output is

    last element of the string: /