473,387 Members | 1,637 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

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_getIntegerAttribute(Object object);
void object_setIntegerAttribute(Object object, int integerAttribute);
void object_unload(Object object);

== In Object.c ==

#include <stdlib.h>

struct ObjectStructure {
int integerAttribute;
};

Object object_create() {return (Object)malloc(sizeof(struct
ObjectStructure));}
int object_getIntegerAttribute(Object object) {return
object->integerAttribute;}
void object_setIntegerAttribute(Object object, int integerAttribute)
{object->integerAttribute = integerAttribute;}
object_unload(Object 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 2725

"Andrew Au" <cs****@gmail.com> 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.com (Andrew Au) wrote in message news:<4c**************************@posting.google. 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_getIntegerAttribute(Object object);
void object_setIntegerAttribute(Object object, int integerAttribute);
void object_unload(Object object);

== In Object.c ==

#include <stdlib.h>

struct ObjectStructure {
int integerAttribute;
};

Object object_create() {return (Object)malloc(sizeof(struct
ObjectStructure));}
int object_getIntegerAttribute(Object object) {return
object->integerAttribute;}
void object_setIntegerAttribute(Object object, int integerAttribute)
{object->integerAttribute = integerAttribute;}
object_unload(Object 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_SIZE == 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.com (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 "significant" 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).privateData)))->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 "deinitialize" it:

Employee employeeInitialize(void);
void employeeDeinitialize(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 employeeInitialize(void);
void employeeDeinitialize(Employee);


Argh, I meant:

void employeeInitialize(Employee*);
void employeeDeinitialize(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****@moonflare.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_getIntegerAttribute(Object object);
void object_setIntegerAttribute(Object object, int integerAttribute);
void object_unload(Object object);

//== In Object.c ==

#include <stdlib.h>

struct ObjectStructure {
int integerAttribute;
};

Object object_create(void) {
return (Object)malloc(sizeof(struct ObjectStructure)); }
int object_getIntegerAttribute(Object object) {
return object->integerAttribute; }
void object_setIntegerAttribute(Object object, int integerAttribute) {
object->integerAttribute = integerAttribute; }
object_unload(Object 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(int);
int someType_attribute(const someType*);
void someType_destroy(const someType*);
void someType_delete(const someType*);

#endif//GUARD_SOMETYPE_H
cat someType.c #include "someType.h"

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

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

someType* someType_new(int attribute) {
someType* p = (someType*)malloc(sizeof(someType));
return someType_initialize(p, attribute);
}

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

void someType_destroy(const someType* p) { }

void someType_delete(const someType* p) {
someType_destroy(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_destroy(&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(int attribute) {
someType* p = (someType*)malloc(sizeof(someType));
p->Attribute = attribute;
return p;
}

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

inline static
void someType_destroy(const someType* p) { }

inline static
void someType_delete(const someType* p) {
someType_destroy(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
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...
11
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...
4
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
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...
100
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
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...
47
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...
139
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...
275
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
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...

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.