M
Michael Rasmussen
Hi all,
Not sure if this is OT?
I have a function in a library written in C++ which returns a
strdup(s.c_str()) to an application written i C. Running Valgrind on my
C-application shows this results in memory leaks due to the c_str is never
freed.
Example:
Foo.h
#ifdef __cplusplus
class Foo {
public:
std::string getString() { return s; }
private:
std::string s;
};
#else
typedef struct Foo Foo;
#endif
#ifdef __cplusplus
extern "C" {
#endif
extern char *cplusplus_getString(Foo *); // C++ call-back
extern char *get_string(Foo *); // C function
#ifdef __cplusplus
}
#endif
Foo.cc
char *cplusplus_getString(Foo *foo)
{
std::string s;
s = foo->getString();
return strdup(s.c_str()) // this is coursing memory leaks.
}
main.c
char *get_string(struct Foo *foo)
{
return cplusplus_getString(foo);
}
int main()
{
struct Foo *foo;
printf("%s\n", get_string());
return 0;
}
Not sure if this is OT?
I have a function in a library written in C++ which returns a
strdup(s.c_str()) to an application written i C. Running Valgrind on my
C-application shows this results in memory leaks due to the c_str is never
freed.
Example:
Foo.h
#ifdef __cplusplus
class Foo {
public:
std::string getString() { return s; }
private:
std::string s;
};
#else
typedef struct Foo Foo;
#endif
#ifdef __cplusplus
extern "C" {
#endif
extern char *cplusplus_getString(Foo *); // C++ call-back
extern char *get_string(Foo *); // C function
#ifdef __cplusplus
}
#endif
Foo.cc
char *cplusplus_getString(Foo *foo)
{
std::string s;
s = foo->getString();
return strdup(s.c_str()) // this is coursing memory leaks.
}
main.c
char *get_string(struct Foo *foo)
{
return cplusplus_getString(foo);
}
int main()
{
struct Foo *foo;
printf("%s\n", get_string());
return 0;
}