472,807 Members | 1,660 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,807 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 2608

"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 (4039.22'N, 11150.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: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
0
linyimin
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
0
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
0
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
5
by: DJRhino | last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer) If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _ 310030356 Or 310030359 Or 310030362 Or...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
0
by: Mushico | last post by:
How to calculate date of retirement from date of birth
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

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.