Topic: When to use malloc()?


Author: Kevin.Yeung@f29.n700.z6.ftn.air.org (Kevin Yeung)
Date: 20 Jan 1994 15:27:39 -0600
Raw View
Hello everybody,

I got a problem in handling string in C/C++.  Consider the following
case:

#include <string.h>
#include <conio.h>
main()
{
char *source = "Hello everybody";
char *destination;
int x;

if ((x = getch()) == 65)  // If 'A' is pressed
   destination = strdup(source); // is this line ok?
else
   strcpy(destination, source); // is this line ok as well?

[ stuff omitted]
}

If I enter 'A' (strdup() is called), the program runs fine, otherwise
(strcpy() is called instead), the program fails.  I am aware that some
string handling functions need malloc() to be called beforehand.  So, my
question is, when to use malloc()?  I will be most grateful if you will
kindly teach me.  Thank you.

Regards,
Kevin Yeung
e-mail: kevin.yeung@f29.n700.z6.ftn.air.org


 * Origin: ComputerWorld On-Line - (852) 572-7640  (6:700/29)