To: gapa83 AT udcf DOT gla DOT ac DOT uk Subject: Re: strcpy() bug? From: pfulmek AT email DOT tuwien DOT ac DOT at (Paul FULMEK) Reply-To: pfulmek AT email DOT tuwien DOT ac DOT at Cc: djgpp AT sun DOT soe DOT clarkson DOT edu (djgpp) Date: Wed, 9 Mar 1994 08:52:27 +0000 >>>From: Paul Harness >>>Subject: strcpy() bug? >>> >>>The following program: >>> >>>#include >>>#include >>>int main(void) >>>{ >>> char *element1[]={"length","length"}; You don't ask the Compiler (with capital 'C') to allocate MEMORY for Your element1[]-array. The Compiler only reserves RAM for the 2 POINTERS: element1[0] and element1[1] - That's exactly what You asked it to do. Then the Compiler allocates memory for the constant string "length" only once, as the two strings are identical - the Compiler is a clever one -, and sets both element1[]-pointers to the starting address of this unique string. (Besides, string constants shouldn't be writeable!) If you check the addresses (In common it's a problem with virtual memory, I know) by printf("%X %X\n",&element1[0][0],&element1[1][0]); You'll find out, that in this case both element1[]-pointers point to the same address. That's is Your problem. strcopy() acts correctly: it copies the string "text" to the address, which BOTH element1[]-pointers point at! Initializing with {"length","short"} forces the Compiler to allocate RAM for "length" AND "short", and therefore to set Your element1[]-pointers to different addresses. As You obviously want the Compiler to allocate RAM and set two pointers to addresses of initialized RAM-areas, You should better tell him explicitly to do so. For example char element1[2][7] = {"length","length"}; or char *element1[]; element1[0] = (char *)malloc( sizeof(char)*7 ); element1[1] = (char *)malloc( sizeof(char)*7 ); strcpy( &element1[0][0], "length" ); strcpy( &element1[1][0], "length" ); will work in the desired way. Hopefully this helps, Paul -- Technische Universitaet Wien Institut fuer Werkstoffe der Elektrotechnik Dipl.-Ing. Paul FULMEK Tel. (+43 222) 58801/3955 FAX: (+43 222) 50 41 587 Gusshausstrasse 27-29 Austria - 1040 WIEN