0

The Code is supposed to count the amount of times a substring accours in a longer string and detect the location of the substring in the longer string. My Code seems to work but I am wondering why it worked even without allocating memory to index. Intuitvely i thought that because its not clear how many elements index has i would have to allocate memory to it. I appreciate your answers.

#include <stdio.h>
#include <string.h>

int *count_substr2(char *str, char *substr){

    int i;
    int counter= 0;
    int *index;

    for(i=0; i< (strlen(str)-1); i++){
        if(str[i]== substr[0] && str[i+1]==substr[1]){
            index[counter]=i;
            counter++;
        }

    }
    return index;
}

int main () {
    
    char *string= "abqervbqyyxöiböxxivxybaböxxrnvrixmxcxpäxyeyoymäab";
    char *substr= "ab";


    int* y =count_substr2(string, substr);
    printf("%d     %d      %d    ", y[0], y[1], y[2]);

    return 0;  
}
kaylum
  • 13,833
  • 2
  • 22
  • 31
  • 1
    It's called Undefined Behaviour. Writing to an invalid pointer is UB. UB means the behaviour is unpredictable - could crash, could get wrong results or could even appear to "work". But it can change at any time and with any unrelated code changes. – kaylum Jun 08 '22 at 00:21

1 Answers1

0

The pointer index is not initialised. It could be zero, or anything else. The code is offsetting that pointer by [counter] and storing values somewhere. If it happens to be pointing to somewhere you don't own, your code will crash with a segmentation violation. But for now, it's just corrupting some area you do own - perhaps the stack, or your heap.

So at the moment, whatever value index is holding is somewhat benign. In the future it may not be. Commonly uninitialised local pointers tend to be filled with whatever was on the stack previously.

There are terrible side-effects of these sorts of bugs. Right here and now, you see no bug. But then ages later (in CPU time at least), the code using a data structure corrupted by this over-write will crash. This can be very expensive to debug.

Kingsley
  • 14,398
  • 5
  • 31
  • 53