/*
Author : stoneJam*/
//----------------------------------------------------------
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/* return 1 if str is "1", 0 otherwise */
int checkIf1(char *str) {
char *newstr = (char*)malloc(strlen(str) + 1);
// ERROR #1
// strcat(newstr, str); /* set newstr to str */
// to set newstr to str we should use
// strcpy(newstr, str);
strcpy(newstr, str); /* set newstr to str */
if (strcmp(newstr, "1") == 0) { /* newstr is "1" */
//a memory leak occured here
free(newstr); // add this statement to free newstr before return
return 1;
}
free(newstr);
return 0;
}
void main() {
char *strArr[4] = {"1", "2", "3", "4"};
int i;
for(i = 0; i < 4; i++) {
printf("%d\n", checkIf1(strArr[i]));
}
}
/*
Author : stoneJam*/
//----------------------------------------------------------
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct data {
char *str1, *str2;
};
/* returns two strings concatenated if they are not the same, NULL otherwise */
char *mergeSingleIfDifferent(char *s1, char *s2) {
char *str = (char *) malloc(strlen(s1) + strlen(s2) + 1);
if (strcmp(s1, s2) == 0) { /* strings are equal */
// ERROR #2
// if str is assigned to NULL
// the memory malloc to it will never be freed
// free str before set str to NULL
free(str);
str = NULL;
}
else {
strcpy(str, s1);
strcat(str, s2);
}
return str;
}
/* copies merged strings (or NULL) into array of strings passed in (results) */
void mergeArrayIfDifferent(char *results[], char *strA1[], char *strA2[], int size) {
int i;
for(i = 0; i < size; i++) {
results[i] = mergeSingleIfDifferent(strA1[i], strA2[i]);
}
}
void printAndFree(int c, char *str) {
if (str != NULL) {
printf("%d: %s\n", c, str);
free(str);
}
}
void main() {
char *strArr1[8] = {"1", "2", "3", "4", "5", "6", "7", "8"};
char *strArr2[8] = {"a", "2", "c", "4", "e", "6", "g", "8"};
char *results[8];
int i;
mergeArrayIfDifferent(results, strArr1, strArr2, 8);
for(i = 0; i < 8; i++) {
// ERROR #1
// printAndFree(i, results);
// results's type is char *[8]
// while param2 of printAndFree is char*
printAndFree(i, results[i]);
}
}