Apr 14th, 2005, 21:45 | #1 |
Senior Member
注册日期: Jul 2004
帖子: 133
|
C问题请教:
2000: char * getbuf() 2001: { 2002: char buff[8]; 2003: /* unspecified, buff defined here *./ 2051: return (char *) buff; 2055: } 1. Is there an alternative, but equivalent, way to write line 2000? If so, what is it? 2. Is getbuf() a reasonable function? 3. Will getbuf() execute at all? 4. Please comment on line 2051. 5. Is getbuf() good practice, and why? |
|
Apr 14th, 2005, 22:55 | 只看该作者 #2 | |
Senior Member
注册日期: Sep 2004
帖子: 109
声望: 10
|
引用:
1. Not sure what you mean, it can be written as char* getbuf() ? 2. Not sure what you mean again. Depends on what you want to do with it. 3. It will execute but will cause a memory error. 4. It's returning a pointer to a mem location on stack. The mem allocated on stack will be destroyed after line 2051 and hence the caller is now having a pointer to an already 'destroyed' memory cells. The caller may behave normally most of the time if the over all application is relatively queisent. But at times it would crash 'mysteriously'. 5. getbuf() does not take any arguments. To return a pointer to the buffer, it has to either use some global memory or it has to use malloc to get mem on the heap. Using global is not desirable in most cases. Using malloc in this context is slightly better if a corresponding function freebuf(char *) is made available to the caller. My preference would be a function like boolean getbuf( char* pbuf, /* IN/OUT pointer to buffer */ int sizeOfBuf /* Max size to fill */ ) { .... // return whether it's success or not. } |
|
|
Apr 14th, 2005, 23:38 | 只看该作者 #4 | |
Senior Member
注册日期: Sep 2004
帖子: 109
声望: 10
|
引用:
processes are using this function, there's a risk of caller A getting a value that should belong to caller B. |
|
|
Apr 15th, 2005, 15:56 | 只看该作者 #5 | |
Junior Member
注册日期: Apr 2005
帖子: 27
声望: 2338
|
not thread safe
引用:
|
|
|