Is this the best (only?) way to give a fresh char *ptr a strlen of 0?
Code:ptr=malloc(0); free(ptr);
Printable View
Is this the best (only?) way to give a fresh char *ptr a strlen of 0?
Code:ptr=malloc(0); free(ptr);
You need at least a buffer of 1. Then just set the first element to 0.
gg
So it has to malloc'd anyway? I might as well just use the free call then.
Just assign "" to it.
From the standard
In other words, it could end up pointing anywhere. So strlen() would probably segfault and/or return unpredictable results.Quote:
Originally Posted by 7.20.3 C99
The best way (IMO) is what Codeplug suggested:
It doesn't have to be on the heap either (which is pretty obvious ;))Code:char * ch = malloc(1);
if(ch == NULL)
{
/* do something */
}
*ch = '\0';
/* ... do whatever with ch, resize if need be */
free(ch);
Code:char nul = '\0';
char * ch = &nul;
/* do whatever with ch */