Re: Dynamic lists of strings in C



On 31 Mar, 15:54, hlubenow <hluben...@xxxxxxx> wrote:

char *strMalloc(unsigned int s);
char *strRealloc(char *a, unsigned int s);
struct list *listMalloc(unsigned int s);

The above parameters should be of type size_t,
not unsigned.

<snip>
/* Please call this, if you don't need the list anymore: */
a = clearList(a);

Perhaps clearList is misnamed. Does this free the memory
associated with a? Given the name, I would expect it
not to, but you are using it as if it does.


char *strMalloc(unsigned int s)
{
/* Allocates memory for a string, testing if allocation has
been successfull. */

char *a;
if ((a = (char *) malloc(s * sizeof(char))) == NULL)
{
puts("Error allocating memory.");
exit(1);
}

1) Error messages should go to stderr, not stdout.
2) If you exit, you should exit with EXIT_FAILURE,
but you shouldn't exit here. You should
instead return an error value. (eg NULL).
3) Sizeof(char) is always 1. It makes sense to call
"malloc( s * sizeof *a)", but it pointless to call it
with sizeof(char).


--
Bill Pursell


.



Relevant Pages