0

Here in this code, the character length is changing suddenly. Before introducing char file the strlen(str) was correct. As I introduced the new char file the strlen value of variable str changes.

#include <unistd.h>
#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;

int main(){

    char buf[BUFSIZ];

    if(!getcwd(buf,BUFSIZ)){
            perror("ERROR!");
    }

    cout << buf << endl;

    char *str;
    str = new char[strlen(buf)];
    strcpy(str,buf);
    strcat(str,"/");
    strcat(str,"input/abcdefghijklmnop");
    cout << str << endl;
    cout << strlen(str) << endl;

    char *file;
    file = new char[strlen(str)];
    cout << strlen(file) << endl;
    strcpy(file,str);
    cout << file << endl;
}

1 Answers1

1

Your code has undefined behavior because of buffer overflow. You should be scared.

You should consider using std::string.

  std::string sbuf;
  {
      char cwdbuf[BUFSIZ];
      if (getcwd(cwdbuf, sizeof(cwdbuf))
        sbuf = cwdbuf;
      else { 
        perror("getcwd");
        exit(EXIT_FAILURE);
      }
 }
 sbuf += "/input/abcdefghijklmnop";

You should compile with all warnings & debug info (e.g. g++ -Wall -Wextra -g) then use the debugger gdb. Don't forget that strings are zero-byte terminated. Your str is much too short. If you insist on avoiding std::string (which IMHO you should not), you need to allocate more space (and remember the extra zero byte).

str = new char[strlen(buf)+sizeof("/input/abcdefghijklmnop")];
strcpy(str, buf);
strcat(str, "/input/abcdefghijklmnop");

Remember that the sizeof some literal string is one byte more than its length (as measured by strlen). For instance sizeof("abc") is 4.

Likewise your file variable is one byte too short (missing space for the terminating zero byte).

file = new char[strlen(str)+1];

BTW on GNU systems (such as Linux) you could use asprintf(3) or strdup(3) (and use free not delete to release the memory) and consider using valgrind.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547