static pointer memory leaks

Flaviu_ 971 Reputation points
2024-03-04T12:11:36.01+00:00

I have the following code:

#ifdef __cplusplus
extern "C" {
#endif
	static SomeClass* SomeClass_instance = NULL;
	void PrepareInstance()
	{
		if (NULL == SomeClass_instance)
		{
			SomeClass_instance = new SomeClass;
		}
	}
	void SomeClass_someMethod(const int id)
	{
		PrepareInstance();
		SomeClass_instance->SomeClass_someMethod(id);
	}
#ifdef __cplusplus
}
#endif

How can I solve memory leaks (SomeClass_instance) using C++98 only? I mean, without smart pointers ...

Basically this code is a C++ to C bridge, for an very old code.

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,683 questions
0 comments No comments
{count} votes

Accepted answer
  1. RLWA32 44,931 Reputation points
    2024-03-04T12:25:53.0433333+00:00

    You can use a function (e.g., DeleteInstance) that destroys the SomeClass object.

    The client code would call DeleteInstance when it is finished using the functions that invoke SomeClass object methods.

    I suggest you make PrepareInstance a required initialization function without embedding its use in other functions. The other functions like SomeClass_method can check for a valid SomeClass_instance pointer and return an error if it has not been initialized.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.