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: Bob Plantz <plantz at cds1 dot net>
- To: "Vardhan, Sundara (GE Infra, Energy)" <sundara dot vardhan at ge dot com>
- Cc: gcc-help at gcc dot gnu dot org
- Date: Tue, 17 Jun 2008 18:13:30 -0700
- Subject: Re: problems with char * return from a function
- References: <8E460D1B58F94945A20AA70D4D41430D052DE9BF@ALPMLVEM08.e2k.ad.ge.com>
On Wed, 2008-06-11 at 20:52 -0400, Vardhan, Sundara (GE Infra, Energy)
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.
> Thanks in advance
>
> With Regards
>
> Vardhan
>
Some of the responses are incorrect. The only thing being passed to x
and to strcpy are addresses. I simulated this with:
#include <stdio.h>
#include <string.h>
char *x(char *n, char *m)
{
char *return_val=NULL;
if (0)
return_val=m;
else
return_val=n;
return(return_val);
}
int main()
{
char a[100];
strcpy(a,x("sample text","default text"));
printf("%s\n", a);
return 0;
}
It works with either if(0) or if(1). Here is the 64-bit assembly
language with some explanatory comments added:
.file "copy_string.c"
.text
.globl x
.type x, @function
x: # char
*x(char *n, char *m)
pushq %rbp
movq %rsp, %rbp
movq %rdi, -24(%rbp) # save m
movq %rsi, -32(%rbp) # save n
movq $0, -8(%rbp)
movq -24(%rbp), %rax # load m
movq %rax, -8(%rbp) # return_val=m;
movq -8(%rbp), %rax # return(return_val);
leave
ret
.size x, .-x
.section .rodata
.LC0:
.string "default text"
.LC1:
.string "sample text"
.text
.globl main
.type main, @function
main:ï # int
main()
pushq %rbp
movq %rsp, %rbp
subq $112, %rsp # a[100];
movl $.LC0, %esi # address of "def...xt"
movl $.LC1, %edi # address of "sam...xt"
call x # x("sam...xt","def...xt")
movq %rax, %rsi # address returned by x
leaq -112(%rbp), %rdi # address of a[]
call strcpy # strcpy(a,ïaddress returned by x);
leaq -112(%rbp), %rdi # address of a[]
call puts # printf("%s\n", a);
movl $0, %eax # return 0;
leave
ret
.size main, .-main
.ident "GCC: (GNU) 4.2.3 (Ubuntu 4.2.3-2ubuntu7)"
.section .note.GNU-stack,"",@progbits
(The assembly language was generated with
-fno-asynchronous-unwind-tables -fno-stack-protector -O0 -S to avoid
extraneous code.)
It clearly shows that the only char array being allocated is in main.
(It allocates 112 bytes because the x86-64 ABI specifies that the stack
pointer should be on a 16-byte boundary when another function is
called.)
My first thought is that the a array is too small. Please don't be
offended by my suggestion. I've made such silly mistakes many times. :-)
-- Bob