Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!usc!snorkelwacker.mit.edu!apple!mdtaylor From: mdtaylor@Apple.COM (Mark David Taylor) Newsgroups: comp.sys.mac.programmer Subject: Re: Quick Question - Strings Message-ID: <11533@goofy.Apple.COM> Date: 14 Dec 90 21:12:32 GMT References: <32027.276537C6@stjhmc.fidonet.org> <90347.101213CXT105@psuvm.psu.edu> <1990Dec13.183037.655@eng.umd.edu> Organization: Apple Computer Inc., Cupertino, CA Lines: 50 In article <1990Dec13.183037.655@eng.umd.edu> russotto@eng.umd.edu (Matthew T. Russotto) writes: >> >> strcpy(test, "\pHello"); /* \p indicates a Pascal string */ > >NONONONONONONONONO! > >"A string beginning with "\p" or "\P" is a Pascal string. It is not terminated >with a null byte". That strcpy can copy tons of characters and write all over >memory. Try > >strncpy(test, "\pHello", 6); Or perhaps: strcpy(test, "Hello"); c2pstr(test); /* or CtoPstr(test), in THINK C */ Yes, it's less optimal, but also less obfuscated. Also, for the benefit of the original poster, if you just need the string to be initialized to "Hello" at the beginning, you can avoid using strcpy() by defining your string this way: char *test = "Hello"; Also note that strcpy() is not built into C; you have to get it from some library like the ANSI library, or write it yourself. If you're really desperate, you can allocate some memory for test and then just say: test[0] = 'H'; test[1] = 'e'; etc. (ugh!) Fortunately, both MPW C and THINK C come with ANSI libraries. Or, since this is comp.sys.MAC.programmer, you can use Mac toolbox calls if you don't mind using Str255's and StringHandles. Check out NewString and SetString. (Munger, too. And BlockMove.) Of course, we all know that we should limit the use of string constants in our code, right? Ideally, one should create a 'STR ' resource and use GetString() to retrieve the string from the resource fork. (Or a 'STR#' resource and GetIndString().) Personally, I keep to C strings as much as possible and use the ANSI library routines, using c2pstr() when necessary. For those few strings that should stay Pascal strings most of the time, I terminate the string variable name with a 'P' to remind myself. - Mark