...
Non-compliant Code Example 1
In this example, a string of upper case characters is converted to lower all case characters. The pointer to the uppercase string, str is passed to the routine func()
. In this routine, a pointer, temp, is set to str and used convert the string "ABCD"
to "abcd"
. Once the string is converted, temp
is freed and the function returns. However, because temp
references the same storage as str
, when temp was freed so was str. As a result, when str
is freed a second time in main, freed memory may accessed leading to unpredictable program behaviorthe memory referred to by x is mistakingly freed multiple times.
Code Block |
---|
#include <stdlib.h> #include <stdio.h> int func(char *str, size_t sizex = malloc (number * sizeof(int)); if (x == NULL) { char *temp = str; /*str and temp reference same locationHandle Error */ size_t i; for (i = 0; i < size-1; i++) temp[i] += 32; free(temp); return 0; } int main(void) { size_t size = 5; char *str = malloc(size); strncpy(str,"ABCD",size); printf("%s\n",str); /* 1st printing of str */ func(str,size); free(str); return 0; } } /* Manipulate x*/ free(x); y = malloc (number * sizeof(int)); if (y == NULL) { /* Handle Error */ } /* Manipulate y*/ free(x); |
Compliant Solution 1
Only free a pointer to dynamic memory referred to by x once. This can be accomplished in this example by removing replacing the second call to free(str)
in main()
.
Code Block |
---|
#include <stdlib.h> #include <stdio.h> int func(char *str, size_t sizex = malloc (number * sizeof(int)); if (x == NULL) { char *temp = str; /*str andHandle temp reference same location Error */ size_t i; for (i = 0; i < size-1; i++) temp[i] += 32; free(temp); return 0; } int main(void} /* Manipulate x*/ free(x); y = malloc (number * sizeof(int)); if (y == NULL) { size_t size = 5; char *str = malloc(size); strncpy(str,"ABCD",size); printf("%s\n",str); /* 1st printing of str */ func(str,size); return 0; } /* Handle Error */ } /* Manipulate y*/ free(y); |
References
VU#623332, http://www.kb.cert.org/vuls/id/623332