Re: General method for dynamically allocating memory for a string
- From: rlb@xxxxxxxxxxxxxxxxxxxxxx (Richard Bos)
- Date: Thu, 31 Aug 2006 12:52:05 GMT
Frederick Gotham <fgothamNO@xxxxxxxx> wrote:
Randall posted:
#include <stdlib.h> // for malloc() and free()
#include <string.h> // for strncpy()
#include <sys/types.h> // for size_t
Non-standard header. "stddef.h" contains "size_t".
So so <stdlib.h>, <string.h>, and...
#include <stdio.h> // for printf()
.... <stdio.h>.
It is not often necessary to #include <stddef.h>. It is very rarely
necessary to do so just for the declaration of size_t. All headers whose
functions need it also declare it themselves, and it's a rare program
that does not use one of those headers.
char * substr(char * string, size_t start, size_t end);
First parameter should be "pointer to const".
No, it shouldn't, because that's not how the function is defined. It may
be a wise idea to _define_ it as a pointer to const char, or even a
const pointer to const char, and then also declare it as such, but
"should" is too strong.
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.
// calculate the total amount of memory needed
// to hold the substring.
// Algo: end - start + null terminator
size_t subStringSize = end - start + 1;
Perhaps you should have written:
size_t len = end - start;
And then added the +1 only when malloc'ing.
Why?
Richard
.
- Follow-Ups:
- References:
- Re: General method for dynamically allocating memory for a string
- From: Frederick Gotham
- Re: General method for dynamically allocating memory for a string
- From: Randall
- Re: General method for dynamically allocating memory for a string
- From: Frederick Gotham
- Re: General method for dynamically allocating memory for a string
- Prev by Date: Re: General method for dynamically allocating memory for a string
- Next by Date: Re: Redirection issue
- Previous by thread: Re: General method for dynamically allocating memory for a string
- Next by thread: Re: General method for dynamically allocating memory for a string
- Index(es):
Relevant Pages
|