473,506 Members | 13,088 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dynamic char* allocation, malloc and free.

Hi,

I am fairly new to C programming and would like to ask a little help
with the following problem.

I am writing a simple ring buffer, implemented as an array of char *.

char* ringbuffer[BUFFLEN];

When I receive a new message (of type char*) I need to make a copy of
the contents of the string in case anyone tampers the original char* (I
have done this by writing a safe string copy routine that takes into
account that the original string may not be null terminated and my
attempt to malloc enough space for the copy may fail).

All well and good so far. I have allocated space for my copy of the
original string and inserted it into my ring buffer at the correct
position.

ringbuffer[end] = message;

When I pop my message off of the ring buffer I do the following

char* message = ringbuffer[start];

Now, here is where I have a problem. I may not be able to process the
whole of my message. In this case I have to replace whatever remains of
the string back in the ringbuffer. I do this by shifting the message
pointer (array index) along by the number of bytes I have processed.

int processed_bytes = dosomething(message);

if (processed_bytes < strlen(message)) {
/* increment message poinmter
message = message + processed_bytes)
}
else {
/* Message processing complete, free memory */
free(message);
}

Will me call to free() free all of the memory allocated to message
during the malloc() call if I have subsequently incremented the message
pointer or will I get a memory leak?

Many thanks for any help.

Lawrie

Nov 14 '05 #1
4 2507
"Lawrie" <st*********@hotmail.com> wrote:
int processed_bytes = dosomething(message);

if (processed_bytes < strlen(message)) {
/* increment message poinmter
message = message + processed_bytes)
}
else {
/* Message processing complete, free memory */
free(message);
}

Will me call to free() free all of the memory allocated to message
during the malloc() call if I have subsequently incremented the message
pointer or will I get a memory leak?


If the pointer you pass to free() isn't the same pointer you got from
malloc() (or realloc(), or calloc()), you get undefined behaviour. This
means that in theory it might work; in practice, you'll most likely get
a segfault.
You could get around this by adding a field to your array to remember
the original pointer, or the offset; or by malloc()ing some new memory
and copying the remaining message to it; or, probably the best solution,
by moving the end of the message to the beginning (optionally followed
by realloc()).

Richard
Nov 14 '05 #2
"Lawrie" <st*********@hotmail.com> wrote:
# Hi,
#
# I am fairly new to C programming and would like to ask a little help
# with the following problem.
#
# I am writing a simple ring buffer, implemented as an array of char *.
#
# char* ringbuffer[BUFFLEN];

# Now, here is where I have a problem. I may not be able to process the
# whole of my message. In this case I have to replace whatever remains of
# the string back in the ringbuffer. I do this by shifting the message
# pointer (array index) along by the number of bytes I have processed.

Use two pointers.

struct{char *base,*curr;} ringbuffer[BUFFLEN];

ringbuffer[i].base is assigned the mallocked block address and
ringbuffer[i].base is initialised to this. Advance .curr. When
you're done free .base.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
If your job was as meaningless as theirs, wouldn't you go crazy too?
Nov 14 '05 #3
On 6 Jun 2005 06:07:43 -0700, Lawrie
<st*********@hotmail.com> wrote:
Now, here is where I have a problem. I may not be able to process the
whole of my message. In this case I have to replace whatever remains of
the string back in the ringbuffer. I do this by shifting the message
pointer (array index) along by the number of bytes I have processed.

int processed_bytes = dosomething(message);

if (processed_bytes < strlen(message)) {
/* increment message poinmter
message = message + processed_bytes)
}
else {
/* Message processing complete, free memory */
free(message);
}

Will me call to free() free all of the memory allocated to message
during the malloc() call if I have subsequently incremented the message
pointer or will I get a memory leak?


So you pass to free() a pointer which is not the same as the one
returned by malloc()? That will not have good results, free() has no
way of getting back to the original pointer, so it will be undefined
behaviour (if you're lucky it will crash in the free(), if you're
unlucky all sorts of weird behaviour may result at some later time).

Basically you need to preserve the pointer returned by malloc(). One
way of doing that might be to save an offset with each pointer in
your ring buffer. Another might be to have a single offset variable
which is set to non-zero when the head message has been partially
processed. Another might be to put a single nul character at the start
of each message, with the message itself following and the pointer in
the ring buffer pointing to the start of the message data (assuming that
data doesn't contain a nul), and on releasing the storage scan backwards
for the nul character at the start.

Which method is best for your application is up to you, but hopefully
this may give you ideas (there are probably many other ways to achieve
it).

Chris C
Nov 14 '05 #4
On Mon, 06 Jun 2005 14:07:59 +0000, SM Ryan wrote:
"Lawrie" <st*********@hotmail.com> wrote:
# Hi,
#
# I am fairly new to C programming and would like to ask a little help
# with the following problem.
#
# I am writing a simple ring buffer, implemented as an array of char *.
#
# char* ringbuffer[BUFFLEN];

# Now, here is where I have a problem. I may not be able to process the
# whole of my message. In this case I have to replace whatever remains of
# the string back in the ringbuffer. I do this by shifting the message
# pointer (array index) along by the number of bytes I have processed.

Use two pointers.

struct{char *base,*curr;} ringbuffer[BUFFLEN];

ringbuffer[i].base is assigned the mallocked block address and
ringbuffer[i].base is initialised to this. Advance .curr. When
you're done free .base.


You don't need a curr pounter for every element of the ringbuffer, just
the one you're reading from. So this can be a single variable separate
from the array.

Lawrence

Nov 14 '05 #5

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

Similar topics

43
3353
by: M-One | last post by:
See subject: how do I calloc (and free the memory, if that's not free(my_bytes);) this? TIA!
5
4129
by: Bill Carson | last post by:
I'm trying to dynamically allocate memory to an array of strings with the following (incomplete, for reference only) : int nLines, nChars, m, n, Cols.sTcolumn ; char ***sAtt; sAtt = (char...
10
442
by: meital | last post by:
I need to implement these functions: void *malloc(int size); void free(void* p); using the functions below: void* malloc_os(int size); void free_os(int size, void* p);
10
2755
by: s.subbarayan | last post by:
Dear all, I happen to come across this exciting inspiring article regarding memory leaks in this website: http://www.embedded.com/story/OEG20020222S0026 In this article the author mentions:...
2
5325
by: collinm | last post by:
hi i expect to find 7 file on a folder... maybe less, maybe more... i can surely put this number to 1... but i think doing some realloc will be expensive... after 7 files, i need to use...
28
6008
by: hlubenow | last post by:
Hello, I really like Perl and Python for their flexible lists like @a (Perl) and a (Python), where you can easily store lots of strings or even a whole text-file. Now I'm not a...
1
7945
by: Peterwkc | last post by:
Hello all expert, i have two program which make me desperate bu after i have noticed the forum, my future is become brightness back. By the way, my problem is like this i the first program was...
18
2989
by: welch.ryan | last post by:
Hi all, Having a problem with addressing large amounts of memory. I have a simple piece of code here that is meant to allocate a large piece of memory on a ppc64 machine. The code is: /*...
14
3812
by: vivek | last post by:
i have some doubts on dynamic memory allocation and stacks and heaps where is the dynamic memory allocation used? in function calls there are some counters like "i" in the below function. Is...
21
2877
by: arnuld | last post by:
I have created a program to print the input words on stdout. Input is taken dynamically from stdin. In each word, each input character is allocated dynamically. I have ran this program with a file...
0
7105
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
7371
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7023
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...
0
5617
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
4702
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3188
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...
0
3178
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
757
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
410
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.