ActiveState Code

Recipe 576774: util,maybe a lib


keep on working to avoid dimentia

C
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <string.h>
#include <ctype.h>

#include "jy_common.h"


char *itoa(int i){
    char *buf = calloc(sizeof(i)+1, 1);
    if(buf == NULL){
        return NULL;
    }

    sprintf(buf, "%d", i);
    return buf;
}


char *trim(char *string){
    if(NULL == string){
        return NULL;
    }
    int start = 0;
    int end = strlen(string);
    while( start < end && (isspace(string[start]) || isblank(string[start])) ){
        start++;
    }

    while( end > start && (isspace(string[end-1]) || isblank(string[end - 1]))){
        end--;
    }

    char *ret = calloc(end - start +1, sizeof(char));
    if(NULL == ret){
        perror("calloc for trim\a");
        return NULL;
    }

    return strncpy(ret, string+start, end-start);

}

Comments

  1. 1. At 3:33 a.m. on 31 aug 2009, Gabriel Genellina said:

    ????????????????????????

    calloc(sizeof(i)+1, 1)
    

    On a 32 bits system, sizeof(i)==4. Call your itoa function with anything greater than 9999 and... kaput!

Sign in to comment