0

This code throws the EXC_BAD_ACCESS Error when trying to set t[j]to t[j+1] and i dont understand why?

#include <stdio.h>
#include <ctype.h>

int strclean(char *t){
    int tmp2 = 0;
    if(t == NULL){
        return -1;
    }
    int i = 0;
    while(t[i] != NULL) {
        if (isprint(t[i]) == 0 || isspace(t[i])) {
            tmp2++;
            for(int j = i; t[j]!=NULL;j++){
                t[j] = t[j+1];               //throws error
            }
            i--;
        }
        printf("%c\n", t[i]);
        i++;
    }
    t[i] = "\0";
    return tmp2;
}

int main() {
    printf("%d\n", strclean("fg h ear p\n"));
    return 0;
}

thank you for the help in advance!

frankakn_7
  • 31
  • 1
  • 6
  • 2
    Literal strings are effectively *read-only* in C. Attempting to modify a literal string leads to *undefined behavior*. – Some programmer dude Feb 03 '20 at 07:54
  • 1
    Also note that `NULL` is the null *pointer*, not the string null terminator. The null terminator is the character `'\0'`. And that `"\0"` is very different from `'\0'`. – Some programmer dude Feb 03 '20 at 07:55
  • thank you! I was so confused as to what was wrong, since all I got when i googled this were situations where the memory was not properly allocated. – frankakn_7 Feb 03 '20 at 08:00
  • When in your `for` loop `t[j]` will be pointing to the last `t` element, `t[j] != NULL` is true, but `t[j+1]` are out of `t` bounds, so you are reading out of `t`. – SuperG280 Feb 03 '20 at 08:03

0 Answers0