This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: problems with char * return from a function
- From: Andrew Haley <aph at redhat dot com>
- To: eus at member dot fsf dot org
- Cc: "Vardhan, Sundara \(GE Infra, Energy\)" <sundara dot vardhan at ge dot com>, GCC Help Mailing List <gcc-help at gcc dot gnu dot org>
- Date: Mon, 16 Jun 2008 13:43:57 +0100
- Subject: Re: problems with char * return from a function
- References: <865594.57166.qm@web37605.mail.mud.yahoo.com>
Eus wrote:
> Hi Ho!
>
> --- On Thu, 6/12/08, Vardhan, Sundara (GE Infra, Energy) <sundara.vardhan@ge.com> wrote:
>
>> Hi All
>>
>> I am calling a function x within strcpy as follows
>>
>> strcpy(a,x("sample text","default text"));
>>
>> x is defined as follows
>>
>> char * x(char *m, char *n)
>> {
>> char *return_val=NULL;
>> if (check m is in database)
>> return_val=m;
>> else
>> return_val=n;
>> return(return_val);
>> }
>> This causes the array a to have a corrupted string. The string is either m or n but with illegal characters appended.
>> So I tried the following
>> char *temp=NULL
>> temp=x("sample text","default text");
>> strcpy(a,temp);
>>
>>
>> When I printed temp, it looked file, but when I printed a it was garbled. I had initialized as a[0]='\0';
>>
>> The same program works fine in Sun and IBM. Is there anything in GCC that I need to use as flag to have this not occur?
>> Any help or pointers will be greatly appreciated.
>
> It looks like that you have not zeroed your `a'.
> `a[0]='\0';' is not enough.
> Either you do `char a[BUFFER_SIZE] = {0};' when defining `a' or, better, you do `memset(a, 0, BUFFER_SIZE);'
That's a wrong answer: strcpy() copies the zero terminator as well.
The problem is probably with the declaration of a.
To Sundara: we need a *complete* program that shows this problem
Andrew.