473,776 Members | 1,650 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

General method for dynamically allocating memory for a string

I have searched the internet for malloc and dynamic malloc; however, I still
don't know or readily see what is general way to allocate memory to char *
variable that I want to assign the substring that I found inside of a
string.

Any ideas?
Aug 30 '06
94 4772
On Fri, 01 Sep 2006 12:47:27 +0200, in comp.lang.c , jacob navia
<ja***@jacob.re mcomp.frwrote:
>Richard Heathfield wrote:
>jacob navia said:

>>>As you may know, I am not selling anything here,

No, I don't know that. There is considerable evidence to the contrary.

A product for zero dollars and zero cents?
You're confusing "selling" and "recieving money for". People sell
each other things all day every day, without any money changing hands.
For instance, you can sell your knowledge in return for good will.

--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Sep 1 '06 #61
jacob navia wrote:
CBFalconer wrote:
>Revise the example:

T *p;

if (p = malloc(n * sizeof *p) {
T *q;

q = p+1; p = NULL;
dosomethingwith (q);
q--;
....
}

The revised example will not fool the GC since the block can be reached
from q, since it points between the beginning and the end of the block.
Will not fool which GC? The Boehm GC won't get "fooled"
by that only because it's fairly conservative and tends
to err on the side of leakage rather than premature
collection (AIUI, it will compare bits inside objects,
but I'm willing to be convinced otherwise).

Some will definitely get fooled by that (the GC will
track references to objects and won't bother looking
at every possible byte in the object with every
possible alignment - why should it?).

--
goose
Have I offended you? Send flames to root@localhost
real email: lelanthran at gmail dot com
website : www.lelanthran.com
Sep 1 '06 #62
Ian Collins wrote:
<snipped>
>
That's one advantage of the GC library, it imposes minimal overhead and
only logs real or potential leaks.
Or it may not log any at all. Some GC are rather conservative
you know.

--
goose
Have I offended you? Send flames to root@localhost
real email: lelanthran at gmail dot com
website : www.lelanthran.com
Sep 1 '06 #63
On Fri, 1 Sep 2006, Richard Heathfield wrote:
Tak-Shing Chan said:

<snip>
> In any case, it would hide serious errors

What would? You seem to be talking about hypothetical code hiding
hypothetical errors. The actual posted code seems to have passed you by
completely.
Yes, I was talking about hypothetical errors. But this is
the same type of argument you used against malloc casts---the
/hypothetical/ error of missing <stdlib.hwhen an incomplete
program was posted.

Tak-Shing
Sep 1 '06 #64
Tak-Shing Chan said:
On Fri, 1 Sep 2006, Richard Heathfield wrote:
>Tak-Shing Chan said:

<snip>
>> In any case, it would hide serious errors

What would? You seem to be talking about hypothetical code hiding
hypothetical errors. The actual posted code seems to have passed you by
completely.

Yes, I was talking about hypothetical errors.
I wasn't. If you want to start a new thread about hypothetical errors, feel
free.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Sep 1 '06 #65
Richard Heathfield <in*****@invali d.invalidwrites :
Richard Bos said:
>Ben Pfaff <bl*@cs.stanfor d.eduwrote:
>>rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:

<snip>
>The reasoning given in the comment is also bogus. It is a very _bad_
programming habit to start expecting that you can free pointers twice.

You can free a null pointer any number of times you like. I
think that is what the "it" in "delete it more than once" means.

Yes, you can. My point was that relying on this capability by setting
pointers to null after you're done with them is a bad programming habit,
not a good one, because you _will_ get in the habit of calling free() on
any which pointer, with the reasoning that "it'll either be a valid
pointer or null".

True enough - you shouldn't *rely* on it, in the sense of arbitrarily
littering your code with calls to free(). Nevertheless, setting pointers to
NULL after you're done with them is a /good/ habit, not a bad one. It's
called "defence in depth".
I'm not going to say that I disagree with you, but I'm going to offer
a counterargument anyway.

Setting a free()d pointer to NULL can prevent certain kinds of errors
-- or rather, it can prevent the *symptoms* of certain kinds of
errors.

For example:

some_type *ptr = malloc(sizeof *ptr);
...
free(ptr);
...
/*
* Now I don't remember whether I called free(ptr) or not.
* I'll free it here, just in case.
*/
free(ptr);

As written, the second call to free() invokes undefined behavior. In
fact, evaluating ptr in preparation for the call invokes UB; the call
to free() doesn't really have anything to do with it.

If the first free() call were replaced with:

free(ptr);
ptr = NULL;

then the second free() call wouldn't invoke UB. But it would *still*
(probably) be a symptom of a logical error, namely the failure to keep
track of whether you've already called free(). Setting ptr to NULL
after the first free() would mask the symptom of the error; leaving it
alone could *potentially* cause the second free() to blow up, making
the error easier to detect. (Or it could do nothing; such is the
nature of undefined behavior.)

On the other hand, you could legitimately have reached the point of
the second free() by any of several paths, some of which have free()d
the pointer and some of which haven't. In that case, *if* all the
paths that free() it then set it to NULL, then free()ing it again is
harmless and sensible.

I'd probably be more comfortable with a program design that invokes
free() exactly once, if and only if it's needed, but if having your
program do a little unnecessary work at run time makes it easier to
develop, that's not always a bad thing.
>The truly good programming habit, in this case, is to do your bleedin'
bookkeeping, and keep in mind which pointers you have free()d, and which
you haven't.

That's certainly true, but it is also a good idea to recognise that you
might be fallible, and to take precautions against that fallibility. A null
pointer is far more useful than a pointer with an indeterminate value.
In an ideal world, the question would never arise; you wouldn't make
that mistake in the first place, or at least you'd already have
corrected it.

In software intended to be maximally robust (which, I hasten to add,
isn't *always* worth the effort), it probably makes sense to implement
this kind of defense in depth *and* to detect and log cases where
errors were caught by the second or later line of defense.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Sep 1 '06 #66
Keith Thompson wrote:
In software intended to be maximally robust (which, I hasten to add,
isn't *always* worth the effort), it probably makes sense to implement
this kind of defense in depth *and* to detect and log cases where
errors were caught by the second or later line of defense.
This is a very good insight.

Why taking risks?

A function call with a NULL pointer is extremely fast
in this days of GHZ CPUs.

Setting a pointer to null is a single memory write,
absolutely nothing.
Sep 2 '06 #67
Hello Richard:

We will have to agree to disagree. I agree that my code below if/else
is retarded. I agree that it should have been different. This is what
I SHOULD have coded:

if( str2 != NULL )
printf( "str2: %s\n", str2);

free( str2 );
str2 = 0;
....

It sounds like you have the good fortune to work either by yourself or
in a very small team. I currently work on a 500+ developer contract
here in the United States will millions of lines of code. No "cheap
hack" can keep you safe in such an environment. When dealing with
global data in such an environment the above technique can mean the
difference between mission critical system downtime or a harmless
no-op.

This is not meant to foster an absurd programming practice similar to
this:
if( str2 != NULL )
printf( "str2: %s\n", str2);

free( str2 );
str2 = 0;
....
/* not sure if I really freed the memory */
free( str2 ); // Yea! I'm okay!

It is purely a measure of defensive programming. I have learned these
idioms through working in larger teams with varying levels of expertise
with a lot of little updates to the code base. This has worked well
for my team. I would gladly manage the code if I were the sole
maintainer. In my environment I am not. This idiom works for me. Of
course, your mileage may vary.

-Randall

Richard Bos wrote:
Ben Pfaff <bl*@cs.stanfor d.eduwrote:
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
Frederick Gotham <fg*******@SPAM .comwrote:
>
>Randall posted:
if( str2 != NULL ) {
printf( "str2: %s\n", str2 );
} else {
// Setting a null pointer to zero ensures you
// can delete it more than once (free) without
// undefined behavior. This is a good
// programming habit.
str2 = 0;
}
>>
> As Richard Heathfield pointed out, both "else" clauses are redundant.
>
The reasoning given in the comment is also bogus. It is a very _bad_
programming habit to start expecting that you can free pointers twice.
You can free a null pointer any number of times you like. I
think that is what the "it" in "delete it more than once" means.

Yes, you can. My point was that relying on this capability by setting
pointers to null after you're done with them is a bad programming habit,
not a good one, because you _will_ get in the habit of calling free() on
any which pointer, with the reasoning that "it'll either be a valid
pointer or null". That habit will then bite you when you encounter an
exception; e.g., when you make a copy of a pointer and only set one copy
to null, or when you have to work with other people's code which doesn't
nullify any pointers.
The truly good programming habit, in this case, is to do your bleedin'
bookkeeping, and keep in mind which pointers you have free()d, and which
you haven't. Don't just pass any which pointer to any which function,
relying on cheap hacks to keep you "safe".

Richard
Sep 2 '06 #68
"Randall" <ra************ *@gmail.comwrit es:
Hello Richard:

We will have to agree to disagree. I agree that my code below if/else
is retarded. I agree that it should have been different. This is what
I SHOULD have coded:

if( str2 != NULL )
printf( "str2: %s\n", str2);

free( str2 );
str2 = 0;
...
Please don't top-post. See <http://www.caliburn.nl/topposting.html >
(and most of the articles in this newsgroup) for details.

Out of curiosity, is there some reason you use NULL in the comparison
and 0 in the assignment? I would have used NULL for both.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Sep 2 '06 #69
Randall wrote:
We will have to agree to disagree. I agree that my code below if/else
is retarded. I agree that it should have been different. This is what
I SHOULD have coded:

if( str2 != NULL )
printf( "str2: %s\n", str2);

free( str2 );
str2 = 0;
...

[...] It is purely a measure of defensive programming. I have learned these
idioms through working in larger teams with varying levels of expertise
with a lot of little updates to the code base. This has worked well
for my team. [...]
Indeed, its good practice. But its repetitive, wordy and perhaps not
as expressive as you might intend. How about:

printf ("str2: %s\n", strfForPrintf (str2));
safeFree (str2);

where you have the following macros defined:

#define strfForPrintf(s tr) ((str)?(str):"< NULL>")
#define safeFree(str) do { free (str); str = NULL; } while (0)
Richard Bos wrote:
Ben Pfaff <bl*@cs.stanfor d.eduwrote:
You can free a null pointer any number of times you like. I
think that is what the "it" in "delete it more than once" means.
Yes, you can. My point was that relying on this capability by setting
pointers to null after you're done with them is a bad programming habit,
not a good one, because you _will_ get in the habit of calling free() on
any which pointer, with the reasoning that "it'll either be a valid
pointer or null".
You're reaching. In some programming environments you *wrap* your
calls to free(), or you use tools like purify etc, and you get status
reports about attempts to free NULL. I.e., you actually get visibility
into potential programming failures, as opposed to just suffering from
a double free which has UB, and can be difficult to track down or trace
without some effort.
[...] That habit will then bite you when you encounter an
exception; e.g., when you make a copy of a pointer and only set one copy
to null, or when you have to work with other people's code which doesn't
nullify any pointers.
The truly good programming habit, in this case, is to do your bleedin'
bookkeeping, and keep in mind which pointers you have free()d, and which
you haven't. [...]
If you follow your own logic for a second, don't you also have to do
everyone else's book keeping too, since you might be using other
people's code that doesn't nullify pointers? Following
standards/patterns and using safety mechanisms like NULLing pointers is
a far more scalable approach in terms of the number of programmers you
can sustain on a single project.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

Sep 2 '06 #70

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

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.