I expect the code in post #7 has the exact error being pointed out
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int compare(char *string1,char *string2) {
int response = 1;
for (int i=0;i<=strlen(string1);i++) {
printf("Comparing '%c' and '%c'\n", string1[i], string2[i]);
if ( string1[i] != string2[i] ) {
response = 0;
};
};
return response;
};
int main(void)
{
char *s1 = "123456"; // These should be const char but compare() is not
char *s2 = "ABC"; // const correct and I don't want to cast
if (!compare(s1,s2))
printf("wtf Strings are not equal\n");
return 0;
}
Output:
Code:
Comparing '1' and 'A'
Comparing '2' and 'B'
Comparing '3' and 'C'
Comparing '4' and ''
Comparing '5' and 'w'
Comparing '6' and 't'
Comparing '' and 'f'
Edit:
Perhaps this is a better example
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int compare(char *string1,char *string2) {
int response = 1;
for (int i=0;i<=strlen(string1);i++) {
printf("Comparing '%c' and '%c'\n", string1[i], string2[i]);
if ( string1[i] != string2[i] ) {
response = 0;
};
};
return response;
};
int main(void)
{
char *s1 = "123456";
char *s2 = malloc(2);
if (!s2) goto end;
strcpy (s2, "A");
if (!compare(s1,s2))
printf("!=\n");
end:
free(s2);
return 0;
}
Code:
valgrind ./a.out
==2605== Memcheck, a memory error detector
==2605== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==2605== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==2605== Command: ./a.out
==2605==
Comparing '1' and 'A'
Comparing '2' and ''
==2605== Invalid read of size 1
==2605== at 0x401194: compare (hyper.c:7)
==2605== by 0x40124E: main (hyper.c:24)
==2605== Address 0x4a2b042 is 0 bytes after a block of size 2 alloc'd
==2605== at 0x483880B: malloc (vg_replace_malloc.c:309)
==2605== by 0x401227: main (hyper.c:18)
==2605==
Comparing '3' and ''
==2605== Invalid read of size 1
==2605== at 0x4011DB: compare (hyper.c:8)
==2605== by 0x40124E: main (hyper.c:24)
==2605== Address 0x4a2b042 is 0 bytes after a block of size 2 alloc'd
==2605== at 0x483880B: malloc (vg_replace_malloc.c:309)
==2605== by 0x401227: main (hyper.c:18)
==2605==