this is my solution
#include <stdlib.h>
#include <string.h>
char* deletemultiple(const char* str) {
if (str == NULL) {
return NULL;
}
size_t length = strlen(str);
if (length == 0) {
return str;
}
length = length + 1u;
char* s = malloc(length);
if (s == NULL) {
return NULL;
}
size_t j = 0;
for (size_t i = 0; s[i] != 0; i++) {
if (str[i] != str[i+1]) {
s[j++] = str[i];
}
}
s = realloc(s, j+1);
if (s == NULL) {
return NULL;
}
return s;
}
int main(void) {
char str[] = "";
char* s = deletemultiple(str);
free(s);
return 0;
}
it's a program that delete multiple characters (i.e adjacent characters) and return a new allocated string without multiple adjacent characters. This solution works only for strings with length != 0; but if string is "" (i.e an empty string), when I free the memory, I have an error that blocks the program. (i.e A breakpoint instruction (__debugbreak() statement or a similar call) was executed ).
Moreover, I have 2 warnings: one warning reminds me that "realloc might return a null pointer", but I already know that and in fact I've used an if-block to check if it's either null or not.
and the other warning is about "reading invalid data from s, and it's related to this for-loop block:
for (size_t i = 0; s[i] != 0; i++) {
if (str[i] != str[i+1]) {
s[j++] = str[i];
}
}
can somebody explains what does these errors/warnings mean, and how to solve them? in similar exercises, if I'll have these errors again, what should I do?