473,714 Members | 2,552 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Object Oriented Programming in C, Avoid Memory Allocation

Dear all,

I am trying to write a piece of software that use Object Oriented design
and implement it with C, I did the following

== In Object.h ==
typedef struct ObjectStructure * Object;

Object object_create() ;
int object_getInteg erAttribute(Obj ect object);
void object_setInteg erAttribute(Obj ect object, int integerAttribut e);
void object_unload(O bject object);

== In Object.c ==

#include <stdlib.h>

struct ObjectStructure {
int integerAttribut e;
};

Object object_create() {return (Object)malloc( sizeof(struct
ObjectStructure ));}
int object_getInteg erAttribute(Obj ect object) {return
object->integerAttribu te;}
void object_setInteg erAttribute(Obj ect object, int integerAttribut e)
{object->integerAttribu te = integerAttribut e;}
object_unload(O bject object) {free object}

// I am afraid if the above code even compile, since I am simply writing the
code in the news client without a compiler.

While it is good to encapsulate the Object's structure, now, I must always
create the object in a dynamic memory allocation way (obviously, coz' the
outside world has no idea of the structure's size).

Now I am in dillema, I would like to have encapsulation for the object, so
that further changes to the Object does not affect the rest of the code, but
at the same time, I would like to avoid dynamic memory allocation as much as
possible, following the rule that ONLY unknown size of memory (p.s. I don't
have very large memory block) should be dynamically allocated, and any
pieces of dynamic memory should be reused as much as possible. (For
performance issue)

What should I do? At the same time, I would like to seek method refactor my
code so as to minimize memory allocation, are there any suggestion?
Memory Pool is great, and I am already using them.
Nov 14 '05 #1
9 2796

"Andrew Au" <cs****@gmail.c om> wrote

Now I am in dillema, I would like to have encapsulation for the object, so
that further changes to the Object does not affect the rest of the code, but at the same time, I would like to avoid dynamic memory allocation as much as possible, following the rule that ONLY unknown size of memory (p.s. I don't have very large memory block) should be dynamically allocated, and any
pieces of dynamic memory should be reused as much as possible. (For
performance issue)

What should I do? At the same time, I would like to seek method refactor my code so as to minimize memory allocation, are there any suggestion?
Memory Pool is great, and I am already using them.

Write a pair of functions, mymalloc() and myfree(), and use them to allocate
your objects from a big global pool.
When memory / performance constraints bite, tweak these functions. For
instance if you know that you always allocate 10 struct foos of 50 bytes,
then you can create a special pool of 50 byte blocks and allocate from this
efficiently and without any fragmentation.
Nov 14 '05 #2
cs****@gmail.co m (Andrew Au) wrote in message news:<4c******* *************** ****@posting.go ogle.com>...
Dear all,

I am trying to write a piece of software that use Object Oriented design
and implement it with C, I did the following

== In Object.h ==
typedef struct ObjectStructure * Object;

Object object_create() ;
int object_getInteg erAttribute(Obj ect object);
void object_setInteg erAttribute(Obj ect object, int integerAttribut e);
void object_unload(O bject object);

== In Object.c ==

#include <stdlib.h>

struct ObjectStructure {
int integerAttribut e;
};

Object object_create() {return (Object)malloc( sizeof(struct
ObjectStructure ));}
int object_getInteg erAttribute(Obj ect object) {return
object->integerAttribu te;}
void object_setInteg erAttribute(Obj ect object, int integerAttribut e)
{object->integerAttribu te = integerAttribut e;}
object_unload(O bject object) {free object}

// I am afraid if the above code even compile, since I am simply writing the
code in the news client without a compiler.

While it is good to encapsulate the Object's structure, now, I must always
create the object in a dynamic memory allocation way (obviously, coz' the
outside world has no idea of the structure's size).

Now I am in dillema, I would like to have encapsulation for the object, so
that further changes to the Object does not affect the rest of the code, but
at the same time, I would like to avoid dynamic memory allocation as much as
possible, following the rule that ONLY unknown size of memory (p.s. I don't
have very large memory block) should be dynamically allocated, and any
pieces of dynamic memory should be reused as much as possible. (For
performance issue)

What should I do? At the same time, I would like to seek method refactor my
code so as to minimize memory allocation, are there any suggestion?
Memory Pool is great, and I am already using them.


I am thinking of a way through macro expansion

== In Object.h ==
#define OBJECT (Object*)char[OBJECT_SIZE];
#define OBJECT_SIZE;

== In Object.c

// Somewhere
{
assert(OBJECT_S IZE == sizeof(struct ObjectStructure ));
}

Then I could have static Object placed on the heap.
One difference from C++ is that the Object created must be freed, even
it is placed on the stack, it won't automatically destruct.
Nov 14 '05 #3
In article <4c************ **************@ posting.google. com>,
cs****@gmail.co m (Andrew Au) wrote:
Now I am in dillema, I would like to have encapsulation for the object, so
that further changes to the Object does not affect the rest of the code, but
at the same time, I would like to avoid dynamic memory allocation as much as
possible, following the rule that ONLY unknown size of memory (p.s. I don't
have very large memory block) should be dynamically allocated, and any
pieces of dynamic memory should be reused as much as possible. (For
performance issue)


Can you prove that memory allocation/deallocation affects performance in
any significant way, or is this just a guess? And "significan t" means: I
will lose sales because of it, or customers will complain, or I will
have to buy faster and more expensive hardware.

Do whatever makes programming easiest.
Nov 14 '05 #4
Andrew Au wrote:
Now I am in dillema, I would like to have encapsulation for the object, so
that further changes to the Object does not affect the rest of the code, but
at the same time, I would like to avoid dynamic memory allocation as much as
possible [ . . . ]


This is a concern, since static allocation is more efficient (especially
the freeing part) and many calls to functions using such objects locally
could start to have an impact. Fragmentation on the other hand is not a
concern, since this could be fixed with pools or by using a better
memory allocator.

Here's a little trick I once came up with that lets you create both
public and private members in a C data structure. First put something
like this in your header file:

struct employeePrivate {
int age;
int salary;
};

typedef struct {
char* name;
char privateData[sizeof(struct employeePrivate )];
} Employee;

Employee objectCreate();

In other source files, they can access the public "name" element
directly, but in order to touch the private data they would have to
explicitly mess with the privateData array, which is unlikely to happen
accidentally (and easy to locate if someone does it). In the object's
implementation source file, you place this macro:

#define pri(obj, field) \
(((struct employeePrivate *)(&((obj).priv ateData)))->field)

Used like this:

Employee emp = ...;
pri(emp, salary) = pri(emp, age) * 1000;

These accesses will be just as efficient as normal accesses of struct
members, once the compiler has worked things out. All this code is
untested though. I hope this helps.
--
Derrick Coetzee
I grant this newsgroup posting into the public domain. I disclaim all
express or implied warranty and all liability. I am not a professional.
Nov 14 '05 #5
Derrick Coetzee wrote:
typedef struct {
char* name;
char privateData[sizeof(struct employeePrivate )];
} Employee;

Employee objectCreate();


Err, I forgot to mention - the allocation policy here is, like in most
non-OOP C programs, the caller allocates space for the Employee wherever
they like, and instead of having the implementation create and destroy
the object, you have it "initialize " and "deinitiali ze" it:

Employee employeeInitial ize(void);
void employeeDeiniti alize(Employee) ;

--
Derrick Coetzee
I grant this newsgroup posting into the public domain. I disclaim all
express or implied warranty and all liability. I am not a professional.
Nov 14 '05 #6
Derrick Coetzee wrote:
Employee employeeInitial ize(void);
void employeeDeiniti alize(Employee) ;


Argh, I meant:

void employeeInitial ize(Employee*);
void employeeDeiniti alize(Employee* );

--
Derrick Coetzee
I grant this newsgroup posting into the public domain. I disclaim all
express or implied warranty and all liability. I am not a professional.
Nov 14 '05 #7
Derrick Coetzee wrote:
typedef struct {
char* name;
char privateData[sizeof(struct employeePrivate )];
} Employee;


To avoid alignment issues this might be better:

typedef struct {
char privateData[sizeof(struct employeePrivate )];
<public members>
} Employee;

I'm not sure if even that is allowed by the standard, though. But in
your case, all data is private, so it doesn't really matter.
--
Derrick Coetzee
I grant this newsgroup posting into the public domain. I disclaim all
express or implied warranty and all liability. I am not a professional.
Nov 14 '05 #8
In article <news:ch******* ***@news-int.gatech.edu>
Derrick Coetzee <dc****@moonfla re.com> wrote:
Derrick Coetzee wrote:
typedef struct {
char* name;
char privateData[sizeof(struct employeePrivate )];
} Employee;


To avoid alignment issues this might be better:

typedef struct {
char privateData[sizeof(struct employeePrivate )];
<public members>
} Employee;

I'm not sure if even that is allowed by the standard, though.


The second one is guaranteed to work (because the offset of any
structure's first member is guaranteed to be zero, and sizeof()
takes into account any required padding). The first one is indeed
not guaranteed.

(My opinion, though, is that if you want to write C++ code, just write
C++ code. :-) )
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #9
Andrew Au wrote:
I am trying to write a piece of software
that uses Object Oriented design and implement it with C.
I did the following:

//== In Object.h ==

typedef struct ObjectStructure * Object;
You are confused.
An object is *not* a type.
It is an instance of some type.
Object object_create() ;
int object_getInteg erAttribute(Obj ect object);
void object_setInteg erAttribute(Obj ect object, int integerAttribut e);
void object_unload(O bject object);

//== In Object.c ==

#include <stdlib.h>

struct ObjectStructure {
int integerAttribut e;
};

Object object_create(v oid) {
return (Object)malloc( sizeof(struct ObjectStructure )); }
int object_getInteg erAttribute(Obj ect object) {
return object->integerAttribu te; }
void object_setInteg erAttribute(Obj ect object, int integerAttribut e) {
object->integerAttribu te = integerAttribut e; }
object_unload(O bject object) { free object }

// I am afraid if the above code even compile,
since I am simply writing the code in the news client without a compiler.

While it is good to encapsulate the Object's structure,
now, I must always create the object in a dynamic memory allocation way
(obviously, coz' the outside world has no idea of the structure's size).

Now I am in dillema, I would like to have encapsulation for the object
so that further changes to the Object does not affect the rest of the code
but, at the same time, I would like to avoid dynamic memory allocation
as much as possible, following the rule that ONLY unknown size of memory
(p.s. I don't have very large memory block) should be dynamically allocated
and any pieces of dynamic memory should be reused as much as possible.
(For performance issue) What should I do?
At the same time, I would like to seek method refactor my code
so as to minimize memory allocation, are there any suggestion?
Memory Pool is great, and I am already using them.
I would do it this way:
cat someType.h #ifndef GUARD_SOMETYPE_ H
#define GUARD_SOMETYPE_ H 1

#include <stdlib.h>

typedef struct someType {
int Attribute;
} someType;

someType someType_create (int);
someType* someType_new(in t);
int someType_attrib ute(const someType*);
void someType_destro y(const someType*);
void someType_delete (const someType*);

#endif//GUARD_SOMETYPE_ H
cat someType.c #include "someType.h "

// private initializer
someType* someType_initia lize(
someType* p, int attribute) {
p->Attribute = attribute;
return p;
}

someType someType_create (int attribute) {
someType value;
someType_initia lize(&value, attribute);
return value;
}

someType* someType_new(in t attribute) {
someType* p = (someType*)mall oc(sizeof(someT ype));
return someType_initia lize(p, attribute);
}

int someType_attrib ute(const someType* p) {
return p->Attribute;
}

void someType_destro y(const someType* p) { }

void someType_delete (const someType* p) {
someType_destro y(p);
free((void*)p);
}

Now you can write:

#include "someType.h "

int main(int argc, char* argv[]) {
someType anObject = someType_create (13);
// do stuff with anObject
someType_destro y(&anObject);
return EXIT_SUCCESS;
}

Memory is allocated from automatic storage for anObject.

Actually, for simple objects like this, I might write:
cat someType.h

#ifndef GUARD_SOMETYPE_ H
#define GUARD_SOMETYPE_ H 1

#include <stdlib.h>

typedef struct someType {
int Attribute;
} someType;

inline static
someType someType_create (int attribute) {
someType value;
value.Attribute = attribute;
return value;
}

inline static
someType* someType_new(in t attribute) {
someType* p = (someType*)mall oc(sizeof(someT ype));
p->Attribute = attribute;
return p;
}

inline static
int someType_attrib ute(const someType* p) {
return p->Attribute;
}

inline static
void someType_destro y(const someType* p) { }

inline static
void someType_delete (const someType* p) {
someType_destro y(p);
free((void*)p);
}

#endif//GUARD_SOMETYPE_ H

Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2927
by: Martin | last post by:
When was inheritance intruduced into object oriented programming? More generally, does anyone know or have any sources on when the different features were introduced into object oriented programming?
11
9257
by: DrUg13 | last post by:
In java, this seems so easy. You need a new object Object test = new Object() gives me exactly what I want. could someone please help me understand the different ways to do the same thing in C++. I find my self sometimes, trying Object app = Object(); Object *app = Object(); Object app = new Object();
4
1867
by: mihai | last post by:
I wander what is the penalty of speend for using object oriented programming (C++) against the play C. Have a nice day, Mihai
15
2001
by: Earl Higgins | last post by:
The company where I work as a Senior Software Engineer is currently revamping their (1991 era) "Programming and Style Guidelines", and I'm on the committee. The company, in business for over 20 years, writes medical software, which must ultimately pass FDA approval and ISO 9000 certification. The product the document applies to is a large system, (just over 3 million lines of code) running on a variety of platforms (all Unix-ish), and over...
100
5255
by: E. Robert Tisdale | last post by:
What is an object? Where did this term come from? Does it have any relation to the objects in "object oriented programming"?
4
1882
by: Luke Matuszewski | last post by:
Here are some questions that i am interested about and wanted to here an explanation/discussion: 1. (general) Is the objectness in JavaScript was supported from the very first version of it (in browsers) ? What about the new syntax of creating a object using { 'propName1':'propValue1', 'propName2':'propValue2', 'propName3':{ /* another object */ } } - from what version of JScript/JavaScript it was supported (from what browsers versions) ?...
47
5948
by: Thierry Chappuis | last post by:
Hi, I'm interested in techniques used to program in an object-oriented way using the C ANSI language. I'm studying the GObject library and Laurent Deniau's OOPC framework published on his web site at http://ldeniau.web.cern.ch/ldeniau/html/oopc/oopc.html. The approach is very instructive. I know that I could do much of this stuff with e.g. C++, but the intellectual challenge of implementing these concepts with pure ANSI C is relevant to...
139
5948
by: Joe Mayo | last post by:
I think I become more and more alone... Everybody tells me that C++ is better, because once a project becomes very large, I should be happy that it has been written in C++ and not C. I'm the only guy thinking that C is a great programming language and that there is no need to program things object oriented. Many people says also that they save more time by programming projects object oriented, but I think its faster to program them in a...
275
12313
by: Astley Le Jasper | last post by:
Sorry for the numpty question ... How do you find the reference name of an object? So if i have this bob = modulename.objectname() how do i find that the name is 'bob'
0
8801
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8707
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9314
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9074
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9015
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6634
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4464
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3158
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2520
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.