Re: General method for dynamically allocating memory for a string



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/

.



Relevant Pages

  • Re: dh, the daemon helper
    ... some type is a special case, while const ordinarily binds to the ... ie char const * is a pointer to a constant ... no point in returning memory to the malloc heap. ... 2004 is the UNIX standard. ...
    (comp.unix.programmer)
  • Re: dh, the daemon helper
    ... some type is a special case, while const ordinarily binds to the ... ie char const * is a pointer to a constant ... since this is the way UNIX(*) processes work. ...
    (comp.unix.programmer)
  • Re: Q about passing data as a const array
    ... The const on the len parameter is superfluous; ... exactly equivalent to "const char *data", ... void func(const struct mydata foo); ... Applying const to a pointer parameter can be quite useful, ...
    (comp.lang.c)
  • Re: Why "const rect& rhs" is used here?
    ... declared as const, as far as i can see, i also ... char pcStudentFirstName; ... // Example where struct is copied. ... void SetStudentName ...
    (microsoft.public.vc.language)
  • Re: const , and valid converstions of pointers thereto
    ... char const *const *b; ... const char foo = 'F'; ... type qualifiers within a list of specifiers or qualifiers does not ...
    (comp.lang.c)