Imported Upstream version 2.3
[ossec-hids.git] / src / shared / mem_op.c
1 /* @(#) $Id: mem_op.c,v 1.7 2009/06/24 18:53:08 dcid Exp $ */
2
3 /* Copyright (C) 2009 Trend Micro Inc.
4  * All rights reserved.
5  *
6  * This program is a free software; you can redistribute it
7  * and/or modify it under the terms of the GNU General Public
8  * License (version 3) as published by the FSF - Free Software
9  * Foundation
10  */
11
12
13 #include "mem_op.h"
14
15
16 /* Check if String is on array (Must be NULL terminated) */
17 int os_IsStrOnArray(char *str, char **array)
18 {
19     if(!str || !array)
20     {
21         return(0);
22     }
23
24     while(*array)
25     {
26         if(strcmp(*array, str) == 0)
27         {
28             return(1);
29         }
30         array++;
31     }
32     return(0);
33 }
34
35
36 /* Clear the memory of one char and one char** */
37 void os_FreeArray(char *ch1, char **ch2)
38 {
39     /* Cleaning char * */
40     if(ch1)
41     {
42         free(ch1);
43         ch1 = NULL;
44     }
45     
46     /* Cleaning chat ** */
47     if(ch2)
48     {
49         char **nch2 = ch2;
50             
51         while(*ch2 != NULL)
52         {
53             free(*ch2);
54             ch2++;
55         }
56     
57         free(nch2);
58         nch2 = NULL;
59     }
60     
61     return;
62 }
63
64
65 /* os_LoadString: v0.1
66  * Allocate memory at "*at" and copy *str to it.
67  * If *at already exist, realloc the memory and strcat str
68  * on it.
69  * It will return the new string on success or NULL on memory error.
70  */
71 char *os_LoadString(char *at, char *str)
72 {
73     if(at == NULL)
74     {
75         int strsize = 0;
76         if((strsize = strlen(str)) < OS_SIZE_2048)
77         {
78             at = calloc(strsize+1,sizeof(char));
79             if(at == NULL)
80             {
81                 merror(MEM_ERROR,ARGV0);
82                 return(NULL);
83             }
84             strncpy(at, str, strsize);
85             return(at);
86         }
87         else
88         {
89             merror(SIZE_ERROR,ARGV0,str);
90             return(NULL);
91         }
92     }
93     else /*at is not null. Need to reallocat its memory and copy str to it*/
94     {
95         int strsize = strlen(str);
96         int atsize = strlen(at);
97         int finalsize = atsize+strsize+1;
98
99         if((atsize > OS_SIZE_2048) || (strsize > OS_SIZE_2048))
100         {
101             merror(SIZE_ERROR,ARGV0,str);
102             return(NULL);
103         }
104
105         at = realloc(at, (finalsize)*sizeof(char));
106
107         if(at == NULL)
108         {
109             merror(MEM_ERROR,ARGV0);
110             return(NULL);
111         }
112
113         strncat(at,str,strsize);
114
115         at[finalsize-1] = '\0';
116
117         return(at);
118     }
119     return(NULL);
120 }
121
122
123 /* EOF */