0

With the printf statement printf("new s3 string (in locate function) is \"%s\" \n",s3), code works properly

but when printf("new s3 string (in locate function) is \"%s\" \n",s3) is commented, the code returns null

how is printf affecting the return value?

#include <stdio.h>
#include <string.h>

char * locate(char * s1,char * s2,int index) 
{
    printf("s1 string is \"%s\" \n",s1);
    printf("s2 string is \"%s\" \n",s2);

    int i=0,j=0, k;
    char s3[100];    

    while(i<=index)
    {
        s3[i]=s1[i];
        i++;
    }
    k=i;

    while(s2[j]!='\0')
    {
        s3[i]=s2[j];
        i++; j++;
    }

    while(s1[k]!='\0')
    {
        s3[i]=s1[k];
        i++;k++;
    }

    s3[i]='\0';

    //printf("new s3 string (in locate function) is \"%s\" \n",s3);

    return ((char *)s3);
}


int main(void) 
{
    char * s1="my name shwetha";
    char * s2="is ";
    s1=locate(s1,s2,7);

    printf("Final Inserted string S1 is \"%s\" \n",s1);

    return 0;
}
user3078414
  • 1,942
  • 2
  • 16
  • 24
PyRookie
  • 75
  • 2
  • 4
  • Possible duplicate of [returning a local variable from function in C](http://stackoverflow.com/questions/4824342/returning-a-local-variable-from-function-in-c) – Andrew Henle Jul 20 '16 at 21:44

2 Answers2

8

s3 goes out of scope (it leaves the function it was created in), so it has undefined behavior either way. You need to either create s3 in main and pass it in as another parameter, or use heap allocation via malloc() which is managed by the OS.

ameyCU
  • 16,489
  • 2
  • 26
  • 41
Robert
  • 203
  • 1
  • 9
  • Just a suggestion , instead of _"it leaves the function it was created in"_ , it would be suited to say that it is freed from stack as function it is declared in is terminated . – ameyCU Jul 20 '16 at 19:01
1

Your code returns the pointer to the local variable s3. Declared as such, it goes out of scope (gets released from stack memory) on return; when programmer neglects it, it's a common "generator" of program's undefined behavior. Two solutions are possible:

  1. Dynamically allocating (and subsequently freeing) the variable, as suggested in the other answer.
  2. Modifying the storage duration of the variable, by declaring it static char s3[100]

Please, also see this related SO post.

Community
  • 1
  • 1
user3078414
  • 1,942
  • 2
  • 16
  • 24
  • char * s4=s3; return (s4); Will this also work? Because char * is stored in data segment right? So it should be available after exiting the function, correct? – PyRookie Jul 21 '16 at 10:55
  • You only give the returned _pointer_ a local name, @PyRookie, so nothing else should change for the compiler: memory that it points to stays the same. If you are more curious, try to compile into assembly language and compare the resulting codes line by line. (-: – user3078414 Jul 21 '16 at 13:15