Re: General method for dynamically allocating memory for a string



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".



#include <stdio.h> // for printf()

char * substr(char * string, size_t start, size_t end);



First parameter should be "pointer to const".



int main( void ) {

char *str1 = substr("abcdefghijklmnop",2,7);
char *str2 = substr("abcdefghijklmnop",4,15);



Both variables should be const. (You don't want the address to change
before you pass it to "free".)



if( str1 != NULL ) {
printf( "str1: %s\n", str1);
} 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.
str1 = 0;
}

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.



free( str1 );
free( str2 );

return 0;
}

/**
* Note: this function will return a newly allocated string. It
* is your responsibility to delete this memory to prevent a leak.
*
* param "string" - the string you want to extract a substring from.
* param "start" - the array index to begin your substring.

* param "start" - the array index to begin your substring.
* param "end" - the array index to terminate your substring.
*
* On Error: this function returns null;
*/
char * substr( char * string, size_t start, size_t end) {



First parameter should be "pointer to const".



// pointer to the substring on the heap
char *subString;

// 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.



// request enough bytes to store the entire
// substring and null terminator.
subString = malloc( subStringSize );



subString = malloc(len+1);



// test to make sure we got the memory
// from malloc
if( subString != NULL ) {
// Note this copies one extra byte (the
// null terminator's spot) which is garbage.
// We have to terminate this string.
strncpy( subString, string + start, subStringSize );



"memcpy" would be more efficient if you were strict about the length of
the string, e.g.:

assert( strlen(string) - istart >= len );



subString[subStringSize] = '\0';



Here you invoke undefine behaviour by writing past the end of the buffer.

subString[len] = 0;

You should _always_ check array indexes.



}

// This will either be NULL if we didn't get the
// memory from malloc or it will have our substring.
return subString;

} // end function substr

--

Frederick Gotham
.



Relevant Pages

  • Re: strrep() function
    ... It is suppose to resize the caller's passed string if ... > you're doing is replacing a substring with another string. ... pass a pointer to pszBuffer, ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Getting the middle of a string
    ... > I've tried to make a function that returns the middle of a string. ... This is a pointer to a string holding one blank, ... length+1 to ensure there is the extra space for that zero ... Since your prototype did not supply a place for the substring to ...
    (comp.lang.c)
  • [Corrected and Updated] Re: General method for dynamically allocating memory for a string
    ... Richard - bringing up the issue of freeing or deleting memory twice. ... freeing or deleting given a NULL pointer more than once. ... this function will return a newly allocated string. ... // pointer to the substring on the heap ...
    (comp.lang.c)
  • Re: General method for dynamically allocating memory for a string
    ... // Setting a null pointer to zero ensures you ... is your responsibility to delete this memory to prevent a leak. ... // pointer to the substring on the heap ...
    (comp.lang.c)
  • StrPos
    ... I would like to find a function which can provide me the position of a given substring for a string. ... I noticed that the function "StrPos" can return the pointer, but I need a function that can return me the position. ...
    (borland.public.delphi.language.basm)