Re: General method for dynamically allocating memory for a string



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:

#include <stdlib.h>
#include <stddef.h>
#include <assert.h>

char *to_release;

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;

to_release = malloc(iend - istart + 1);

memcpy(to_release,p,iend - istart);

to_release[iend - istart] = 0;

return to_release;
}

int main()
{
puts(CreateSubstring("abcdefghijklmnop",2,7));
ReleaseLastString();

puts(CreateSubstring("abcdefghijklmnop",4,15));
ReleaseLastString();
}

--

Frederick Gotham
.



Relevant Pages

  • Re: Whats the deal with const?
    ... specify the const part. ... The definition of a function parameter as "const char *x" defines that ... argument as a pointer to one or more constant characters. ... int some_func ...
    (comp.lang.c)
  • Re: concurrent sysctl implementation
    ... static int value; ... const Elf_Rela *relalim; ... static const char *basename; ... These are the functions the dynamic linker exports to application ...
    (freebsd-hackers)
  • Re: Warning meaning.
    ... int strcomp(char *, char *); ... int main (int argc, const char * argv) { ... passing argument 1 of 'strcomp' discards qualifiers from ...
    (comp.lang.c)
  • vmailmgr on Fedora Core 1
    ... exec.cc: In function `int presetenv(const char*, ... Steven Schwartz ...
    (Fedora)
  • Re: From Python to c++
    ... class Str: public Any { ... operator const char*() const { ... class Int: public Any { ...
    (comp.lang.python)