Welcome, guest | Sign In | My Account | Store | Cart

keep on working to avoid dimentia

C, 40 lines
 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);

}

1 comment

Gabriel Genellina 12 years, 3 months ago  # | flag

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

calloc(sizeof(i)+1, 1)

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

Created by J Y on Wed, 20 May 2009 (MIT)
C recipes (32)
J Y's recipes (21)

Required Modules

  • (none specified)

Other Information and Tasks