14 August 2011

Never return a local pointer from a function

SA,

I am now try to write some example (will post here) on JNA (Java Native Access), so I am trying to write some simple cpp program...

While I am writing it, I've faced a problem ... And here's the story..

We always hear this phrase : "Never return a local pointer from a function"

Yes I know it good, but I usually forget it..

Here's some example that I took about 30 minutes investigate to know what's wrong!, and finally I realized this rule!:

#include <iostream>
#include <cstring>

using namespace std;

char* sayHelloFor(char*);

int main(void)
{
    
    char* ret = sayHelloFor("Ali");
    
    cout << ret << endl;;
    
    return 0;
}

char* sayHelloFor(char* name)
{
    char* hello = "Hello ";
    char str[40] = {'\0'};      // this is the local arrary/pointer
    strcat(str, hello);
    strcat(str, name);
    
    return str;
}

It returns some corrupted string (GCC on Windows)

And here's the correct code:

#include <iostream>
#include <cstring>

using namespace std;

void sayHelloFor(char*, char**);

int main(void)
{
    char c[40] = {0};
    char* ret = c;
    sayHelloFor("Ali", &ret);
    
    cout << ret << endl;;
    
    return 0;
}

void sayHelloFor(char* name, char** out)
{
    char* hello = "Hello ";
    //char str[40] = {'\0'};      // this is the local arrary/pointer
    strcat(*out, hello);
    strcat(*out, name);
    //return str;
}


Post a Comment