Q:

Fill and return data from read in C++

I would like to know the best way to make the following in c++, please. I have a Parser and a Gather classes; the gather consume the parser.
I have a method in the Parser class to parse my file with three parameters: process ID (int), path (string, char, char*...???) and string format (also I dont know which is best here - string, const string, etc...). 
Its better to create a data[] in the Parse.method and return it, or to pass a reference to method, and keep the data variable in the gather class?
char* ProcInfoParser::parseStatm(const int _processPid, std::string _path, std::string _strFormat) {

    char path[32];
    char* data[2042];
    int tps = sysconf(_SC_CLK_TCK);

    int fd = open(path, O_RDONLY);

    if (fd < 0) {
        perror("open");
        return "-1"; //wrong...
    }

    if (read(fd, data, 2048) == -1) {
        perror("read");
        return "-1"; //wrong...
    }
    close(fd);

    char name[1024];
    long unsigned int utime, virt;
    long int rss;
    sscanf(data, "%*d %s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu"
        " %*u %*d %*d %*d %*d %*d %*d %*u %lu %ld", name, &utime, &virt, &rss); //Iwish to use the _stringFormat variable here...

    return data;
}

I really dont know which one to choose between char (char*...) or string; I also want to make a path with the process ID like string.Format("/proc/(0)/statm",processID); does the sprintf function work like that? Maybe I should take a look at boost...
Thanks in advance

A:

You have several problems here:
char* data[2042];

Is an array of pointers. I don't think that that's what you wanted, you wanted an array of chars, which would be:
char data[2042];

Also, you pass std::strings and return char*, which is not really consistent. If you return std::string - you won't have an issue. You can pass it around by value, and keep it in the class that owns it.
Last but not least - you're returning a pointer to a local variable, which doesn't exist when you exit the function, that's a recipe for trouble. Returning std::string will solve it too.
Bottom line - you're mixing C and C++ code here. Although C++ allows that, it is usually a common source for bugs and mistakes. Why not using C++ streams and strings?

