![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#21 | |
|
Battle Programmer
Join Date: Feb 2006
Location: Bellevue, WA, USA
Posts: 763
Rep Power: 3
![]() |
Quote:
And in the case of DaWei, possibly the most entertaining as well ![]() |
|
|
|
|
|
|
#22 | |
|
Newbie
Join Date: Jun 2006
Posts: 20
Rep Power: 0
![]() |
Quote:
// insert proper .h files, omitted for brevity
using namespace std;
const char * doSomethingWithAString( const char * inString )
{
// please ignore the lack of length checking.
static char internal_string[50];
memcpy( internal_string, inString, strlen( inString ) );
return internal_string;
}
int main()
{
const char * first_string = doSomethingWithAString( "Hello, " );
const char * second_string = doSomethingWithAString( "world!\n" );
cout << first_string << " " << second_string;
return 0;
} |
|
|
|
|
|
|
#23 |
|
Programming Guru
![]() Join Date: Jun 2005
Location: Adelaide, South Australia
Posts: 1,223
Rep Power: 5
![]() |
Hmmm ..... I don't normally resurrect old threads, but someone sent me a PM suggesting I look at the last post in this thread.
The code given by kyoryu yields undefined behaviour, as doSomethingWithAString() does not append a zero byte on the end of internal_string. In practice, what will usually be seen will be typically be the word "world!" on a line of it's own, possibly followed by a lot of random junk, then a space, then the text "world!" on a line of it's own again, again possibly following by a lot of random junk. On some systems, the program will crash, hang, or otherwise die miserably somewhere in the process of doing all this. If kyoru was to change the memset() line to memcpy( internal_string, inString, strlen( inString ) +1); Either way, this example illustrates quite nicely that simply making a local variable static does not ensure the program gives the behaviour the programmer might intend - a lot of people would expect this code to output the line "Hello world!". |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| changing size of an array | Eric the Red | Java | 3 | Apr 3rd, 2006 8:19 PM |
| 2 dimension array of characters | brad sue | C | 8 | Mar 15th, 2006 9:40 AM |
| Returning an Array | Kilo | C# | 3 | Dec 4th, 2005 10:31 PM |
| Installing IPB 2.03 | bh4575 | Other Web Development Languages | 0 | Apr 23rd, 2005 2:36 AM |
| Returning An Array From a Function | ViZioN | C++ | 5 | Feb 21st, 2005 6:45 PM |