Re: Compiler Warning
- From: Barry Schwarz <schwarzb@xxxxxxxx>
- Date: Mon, 01 Dec 2008 19:23:17 -0800
On Mon, 1 Dec 2008 07:35:32 -0800 (PST), s0suk3@xxxxxxxxx wrote:
On Dec 1, 8:55 am, srikar2097 <srikar2...@xxxxxxxxx> wrote:
I have written this small fn. to strip down whitespaces ("\n") a given
string (only leading and trailing).
The program itself might not be foolproof but that is not my concern
right now. When I compile this
I get a warning :--
"string_utils.c:96: warning: function returns address of local
variable.
I have declared the fn. as fn. pointer and this fn. returns the
address of a string array. Why does
the compiler give out this warning? Please help.
Try:
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
// Return value must be manually deallocated
char* xstrip(const char* str)
{
while (isspace((unsigned char) *str) && *str != '\0')
If isspace returns true, can the second conditional expression ever be
false? If isspace returns false, the second expression won't be
evaluated. Why is it there?
++str;
const char* end = str + strlen(str);
Unless you have c99, declarations must precede statements.
while ((isspace((unsigned char) *end) || *end == '\0') && end >
str)
--end;
char* buf = (char*) calloc(1, end - str + 2);
Don't cast the return from calloc (or any standard *alloc).
You are paying to high a price for the single '/0' that survives the
call to strncpy below.
if (!buf)
return NULL;
strncpy(buf, str, end - str + 1);
return buf;
}
Or, if you want to modify the string in-place:
void xstrip(char* str)
{
char* start = str;
while (isspace((unsigned char) *start) && *start != '\0')
The second comparison is still pointless.
++start;
char* end = start + strlen(start);
while ((isspace((unsigned char) *end) || *end == '\0') && end >
start)
--end;
memmove((void*) str, (const void*) start, end - start + 1);
The casts serve no purpose since there is a prototype in scope
(courtesy of string.h)
str[end - start + 1] = '\0';
}
Sebastian
--
Remove del for email
.
- Follow-Ups:
- Re: Compiler Warning
- From: s0suk3
- Re: Compiler Warning
- References:
- Compiler Warning
- From: srikar2097
- Re: Compiler Warning
- From: s0suk3
- Compiler Warning
- Prev by Date: Re: tree example
- Next by Date: Re: slurping in binary data
- Previous by thread: Re: Compiler Warning
- Next by thread: Re: Compiler Warning
- Index(es):
Relevant Pages
|