BEPP
BEPP

Reputation: 955

How to store C type "char *" to c++ vector?

In c++ code, I have to call a C function which is returning "char*". I want to store the return string in a C++ vector.

Since the C function returning "char *" present in a different shared object, I cannot not modify it.

Declaring vector as vector<string> and storing C type char* is fine or is there any better way i can achieve it? I tried the bellow code snippet and don't see any warning or error.

#include<iostream>
#include<vector>
#include<string>
#include<cstring>
#define MAX_LEN 100
using namespace std;

/*
 * In my actual project, the C functions resides in different shared object.
 * So i cannot modify it. Here I just added the function (fun1, fun2 and fun3)
 * in same file to  minimize the code.
 */
extern "C" {
 char* fun1(char *str1) {
        snprintf(str1, MAX_LEN, "%s", "string 1");
        return str1;
 }
 char* fun2(char *str1) {
        snprintf(str1, MAX_LEN, "%s", "string 2");
        return str1;
 }
  char* fun3(char *str1) {
        snprintf(str1, MAX_LEN, "%s","string 3");
        return str1;
 }
}
int main() 
{ 
        vector<string> V_str;  //defined vector which can store string element
        char *str_ptr, buffer[MAX_LEN]="\0";
        str_ptr = fun1(buffer); // adding char* to the vector
        V_str.push_back(str_ptr);
        str_ptr = fun2(buffer);
        V_str.push_back(str_ptr);
        str_ptr = fun3(buffer);
        V_str.push_back(std::string(str_ptr));
        for(unsigned int i = 0 ; i < V_str.size(); i++ ) {
            cout<<V_str[i]<<endl;
        }
        return 0;
}

Output:

string 1
string 2
string 3

Upvotes: 0

Views: 300

Answers (1)

SergeyA
SergeyA

Reputation: 62583

This code is almost fine. The only potential pitfall is the fact that your fun* functions to not accept the length of the buffer. This is unsafe and frowned upon. Normally, function signature would be something like char* fun1(char* buffer, size_t sz) and it would check the size of the buffer before using it.

However, assuming the C function is given (seeming to be the case from the question), and you can't do anything about it, the code is perfectly fine.

Since one of std::string constructors take const char* argument, std::vector<std::string>.push_back(const char*) creates a temporary string and moves it to the vector. From now on, vector owns this string. This is safe and is not subject to any memory leak.

Upvotes: 3

Related Questions