0

I make a function to add character to string and I have the next error message function returns address of local variable please help me, my code below.

int main(int argc, char** argv) 
{
    char* string;
    string ="hola mundo";
    char c ='x';

    string = cadena_mas_caracter(string,c);
    printf("texto sumado %s",string);

    return (EXIT_SUCCESS);
}

char *cadena_mas_caracter(char* cadena, char caracter)
{
    int i=0;
    int largo_texto = strlen(cadena)+1;
    char cadena_nueva[largo_texto+1];


    for( i=0; i < largo_texto; i++)
    {
        cadena_nueva[i] = cadena[i];
        if(cadena[i] == '\0')
        {
            cadena_nueva[i]= caracter;
        }
    }

    return cadena_nueva;
}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Premier
  • 766
  • 2
  • 10
  • 20
  • this will not work, as you're dynamically allocating stack memory in function, and this memory will be freed as soon as you exit from function, you need to allocate heap memory via new/malloc and then free it via delete/free manually – Iłya Bursov Mar 02 '14 at 03:02
  • char cadena_nueva[largo_texto+1]; this is a local variable and scope of local variable within the function. so you can not return address.yes sometimes it may give you correct result if the memory not assigned to other tasks but that does not mean correct. – java seeker Mar 02 '14 at 03:14
  • yes I understand my local varible is detroy when the method finish and I need put the value out of the stack, but why? I'm trying but I not figured it out, somebody could write code to see the correct form please. – Premier Mar 02 '14 at 03:20
  • @Premier: Check my ans, you can make it work if you allocate it on heap. – brokenfoot Mar 02 '14 at 03:23

1 Answers1

4

You SHOULD NOT (although yes, sometimes it CAN return the expected result!) return local variable pointer from a function as it is allocated on stack!

Here's an excellent explanation as to why: Can a local variable's memory be accessed outside its scope?

To make your code work,replace

char cadena_nueva[largo_texto+1]; 

with

char* cadena_nueva = (char*)malloc(sizeof(char)*(largo_texto+1));

Don't forget to free() it when you are done using it


It would really help you if you'd read about heap & stack memory storage:

What and where are the stack and heap? http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html http://www-ee.eng.hawaii.edu/~tep/EE160/Book/chap14/subsection2.1.1.8.html

Community
  • 1
  • 1
brokenfoot
  • 11,083
  • 10
  • 59
  • 80