Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

How to debug this substring matching code?

I am a beginner in C programming, and this is a string matching code I wrote. It aims to find the positions where the substring t appears in the string s and print them. The use of pointers is required.This code scored 94 out of 100 in the OJ test.

#include <stdio.h>
#include <stdlib.h>

int main () {
    char *s = malloc(100005);
    char *t = malloc(100005);

    scanf ("%s%s", s, t);

    char *ptrS = s;
    char *ptrT = t;

    if (s == NULL) {
        free(t);
        return 1;
    }
    if (t == NULL) {
        free(s);
        return 1;
    }

    while ( *ptrS != '\0') {
        if (*ptrT == *ptrS) {
            ptrT++;
            ptrS++;
        } else if (*ptrS != *(ptrT = t)) {
            ptrS++;
        }

        if (*ptrT == '\0') {
            printf("%d ", (ptrS - s) - (ptrT - t));
            ptrS = ptrS - (ptrT - t) + 1;
            ptrT = t;
        }
    }

    free(t);
    free(s);

    return 0;
}

I have tried many test cases that I could think of, and it gives the correct results for all of them. I hope to find any bugs or any test cases that cause it to error.

Answer*

Cancel
5
  • The expression *( ptrS = ( ptrS - ( ptrT - t ) + 1 ) ) != *( ptrT = t ) is undefined behavior due to unsequenced writing and reading of ptrT.
    – interjay
    Commented Nov 26, 2024 at 15:29
  • @interjay Oh, you are right. I will update teh answer, Commented Nov 26, 2024 at 15:35
  • it's very helpful. thanks a lot for your detailed explanation@VladfromMoscow
    – Elliott T
    Commented Nov 26, 2024 at 16:14
  • @ElliottT No at all. We, beginners, should help each other.:) Commented Nov 26, 2024 at 16:16
  • @interjay How about the updated code snippet? Commented Nov 26, 2024 at 16:18