Re: General method for dynamically allocating memory for a string
- From: websnarf@xxxxxxxxx
- Date: 31 Aug 2006 09:49:04 -0700
Frederick Gotham wrote:
smnoff posted:
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?
Unchecked code, may contain an error or two:
(At least ...)
#include <stdlib.h>
#include <stddef.h>
#include <assert.h>
char *to_release;
Are you seriously making this global?
void ReleaseLastString(void)
{
free(to_release);
}
char const *CreateSubstring(char const *const p,
size_t const istart,size_t const iend)
{
int assert_dummy = (assert(!!p),assert(!!istart),assert(!!iend),0);
if(!p[iend+1]) return to_release = 0, p + istart;
Homiesaywhat? What the hell is that if() condition trying to do? And
what is p+istart trying to do? Are you trying to say p += istart?
to_release = malloc(iend - istart + 1);
Ok, so what if istart > iend? And what if to_release contained some
unfreed contents before this call -- wouldn't that lead to a leak?
memcpy(to_release,p,iend - istart);
What if to_release was set to NULL (because of a memory allocation
failure)?
to_release[iend - istart] = 0;
return to_release;
}
--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/
.
- References:
- 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: c code reusability
- Next by Date: Re: C IDE Recommendations
- 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
|