Re: General method for dynamically allocating memory for a string
- From: websnarf@xxxxxxxxx
- Date: 31 Aug 2006 09:41:01 -0700
Randall wrote:
Frederick's code is hard to read and harder to learn from. Here is
some fully checked code with lots of comments.
///////////////////////////////////////////////////////////////////////////////
// file: substr.c
// Note: C++ style comments are allowed for C99 compliant compilers.
///////////////////////////////////////////////////////////////////////////////
Note: C99 compliant compilers are in very short supply. (Though
compilers that *claim* to be C99 compilers is a little higher and those
that accept // comments are even higher.)
#include <stdlib.h> // for malloc() and free()
#include <string.h> // for strncpy()
#include <sys/types.h> // for size_t
#include <stdio.h> // for printf()
[...]
/**
* 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) {
// 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;
// request enough bytes to store the entire
// substring and null terminator.
subString = malloc( subStringSize );
// 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 );
This leads to UB, since you have not established that string + start is
a valid thing to be pointing at.
--
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
- From: Randall
- Re: General method for dynamically allocating memory for a string
- Prev by Date: Re: C IDE Recommendations
- Next by Date: Re: c code reusability
- 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
|