Re: Proper modularization technique
- From: s0suk3@xxxxxxxxx
- Date: Mon, 10 Nov 2008 10:56:52 -0800 (PST)
On Nov 10, 11:51 am, drhowarddrfine <robbelics@xxxxxxxxx> wrote:
I'm unsure the best way to do this. I want to call a function that
will generate a string to be used by the calling routine. Where is
the best place to store that string? iow:
1) Should I set aside an array in the calling routine and have the
function strcpy to that?
No, because
- the way you wrote it, called_function() will have no way to know
how large the passed array is, and thus is likely to write pass the
end of it. Of course, this is easily fixed by having the function
accept an extra argument that represents the array size, but then
there's the possibility that
- the function might need to store more characters than the array
can hold, thus causing truncation. If truncation isn't a problem
(e.g., you can still get the remaining data in a future call, as with
fgets()), then this is a good way to go.
2) Make the string area static for the calling routine?
No, because
- if your application is multi-threaded, this will break things;
- you can't have the function generate two or more strings and hold
them at the same time (in other words, calling the function will
modify what was previously on the array, even if you still need it);
- there's still the issue of truncation.
3) Make the string area global to that file?
No, because
- "global variables are evil." :-)
Would it be better to just malloc to acquire the memory for that and
then release it? Does that cause relative program slow down doing all
that acquire/releasing?
That has the advantage that you can call realloc() to make the buffer
as large as necessary. And yes, allocating on the heap is generally
slower than allocating on the stack, but you probably don't need to
worry about that unless you're doing micro-optimization.
Sebastian
.
- Follow-Ups:
- Re: Proper modularization technique
- From: drhowarddrfine
- Re: Proper modularization technique
- References:
- Proper modularization technique
- From: drhowarddrfine
- Proper modularization technique
- Prev by Date: Re: Question about void pointers
- Next by Date: array size
- Previous by thread: Re: Proper modularization technique
- Next by thread: Re: Proper modularization technique
- Index(es):
Relevant Pages
|