The following C function:
int sprintf ( char * str, const char * format, ... );
writes formatted data to a string. The size of the array pa
I threw this together as an exercise for myself based on DigitalRoss' suggestion. Feel free to merge this with his answer if you have the rep (I don't).
#include
#include
#include
#include
char* createRandstr(void);
int main(void)
{
char* mystr;
char* randomString;
size_t len;
/* Makes a random string of A's */
randomString = createRandstr();
/* 1st pass gets needed size */
len = (size_t)snprintf(NULL, 0, "random string -->%s<--\n", randomString);
mystr = malloc(len);
/* Safely write to mystr with known length 'len' */
snprintf(mystr, len, "random string -->%s<--\n", randomString);
puts(mystr);
free(mystr);
free(randomString);
return 0;
}
char* createRandstr(void)
{
char* randstr;
size_t randlen;
unsigned int i;
srand((unsigned int)time((time_t*)NULL)); /* Seed rand() */
randlen = (size_t)rand() % 50; /* Limit to max of 49 chars */
randstr = malloc(randlen);
for (i=0; i < randlen; i++)
{
randstr[i] = 'A';
}
randstr[randlen - 1] = '\0';
return randstr;
}