Showing posts with label string. Show all posts
Showing posts with label string. Show all posts

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;
}


18 February 2011

stringutil: my c library for string utilities

Hello,

I am working on some task in CGI, I'll try to write some string utility functions to help me simplify task..

this lib is still simple, It just contains 1 non-static function `split`

#ifndef _STRING_UTIL_
#define _STRING_UTIL_

static size_t count(const char*, char);
size_t split(const char *const, const char*, char***);

#endif


#include <string.h>
#include <stdlib.h>
#include "stringutil.h"

static size_t count(const char *str, char ch)
{
    if (str == NULL) return 0;
    size_t count = 1;
    while (*str)
        if (*str++ == ch) count++;
    return count;
}

size_t split(const char *const str, const char* delim, char ***out)
{
    size_t size = count(str, *delim);
    *out = calloc(size, sizeof(char));
    char* token = NULL;
    char* tmp = (char*) str;
    int i=0;
    while ((token = strtok(tmp, delim)) != NULL)
    {
        tmp = NULL;
        (*out)[i] = (char*) malloc(sizeof strlen(token) * 4 /* to solve some bug */);
        strcpy((*out)[i++], token);
    }
    return size;
}