Re: small c problem
On Thu, Jul 01, 1999 at 03:19:05PM +1200, Michael Beattie wrote:
> char *rad_cmd;
> rad_cmd = "number:";
> What now? i.e. rad_cmd+freq_num to give rad_cmd = "number:444"
> strcat()?
This is broken. You should *never* assign a string constant to a non-const
variable! Because if you subsequently try to mutate the string (and you
will) and you are lucky, you will be looking at a core dump. Never, EVER,
mutate a constant! Use -Wwrite-strings with gcc to catch these.
When you work with strings in C, you must *alwys* think about memory
management. My solution to your problem uses malloc():
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int number = 444;
char * string;
const char * origstring = "number:";
size_t string_len;
string_len = 3 /* length of 444 */
+ strlen(origstring)
+ 1 /* for '\0' */;
string = malloc(string_len);
if (string == 0) abort(); /* Ugh. Do better error handling. */
snprintf(string, string_len, "%s%i", origstring, number);
puts(string);
free(string);
return 0;
}
--
%%% Antti-Juhani Kaijanaho % gaia@iki.fi % http://www.iki.fi/gaia/ %%%
"... memory leaks are quite acceptable in many applications ..."
(Bjarne Stroustrup, The Design and Evolution of C++, page 220)
Reply to: