2

So I commented out the scanf part (and just initialized it with my own string), why does it crash if I use scanf? I believe the actual arguments I've put in scanf(); are correct.

#include <stdio.h>
#include <stdlib.h>
int strendmilan(char *s,char *t)
{
    int scntr = 0,tcntr = 0;
    while(*(s+(scntr++)) != '\0')
        ;
    --scntr;
    while(*(t+(tcntr++)) != '\0')
        ;
    --tcntr;
    while(tcntr >= 0)
        if(*(s+scntr--) == *(t+tcntr--))
            ;
        else
            return 0;
    return 1;
}
int main()
{
    char *s,*t; 
    /*
    scanf("%s",s);
    scanf("%s",t);
    */
    s = "HAHAHACOOL";
    t = "COOL";
    if(strendmilan(s,t) == 0)
        printf("NOT");
    else
        printf("YES");
    getch();
}
jantristanmilan
  • 4,188
  • 14
  • 53
  • 69

1 Answers1

7

The problem is that you are sending scanf() a pointer to a buffer (e.g., s) where it can store the information read, but you haven't allocated any buffer space pointed to by s (and same for t)

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

So you can either allocate an array of char for s, or use malloc() to allocate some storage and assign the return value of that call to s.

Levon
  • 138,105
  • 33
  • 200
  • 191
  • But s = "HAHAHACOOL"; t = "COOL"; works even if i dont allocate space – jantristanmilan Sep 09 '12 at 17:13
  • @vincentbelkin that really doesn't change anything I posted. `scanf` wants a pointer to a location where it can store data. You create the pointer, and then immediately call `scanf` *without* having allocated any storage for `s` to point to (and for `scanf` to successfully use). – Levon Sep 09 '12 at 17:16
  • 2
    @vincentbelkin, `t="COOL"` implicitly allocates some memory to store the string literal, then assigns the location of that memory to the pointer variable. `scanf` expects the pointer variable to already point to allocated memory, into which it will place the characters read. – Dave Costa Sep 09 '12 at 17:17
  • I think i'm misunderstanding something, but doesn't s = "HAHA"; require me to use malloc(); to allocate storage space too? why does it work? – jantristanmilan Sep 09 '12 at 17:18
  • @vincentbelkin It's a string literal (think of it as a constant if that helps). Also see DaveCosta's comment. Also, even if this worked, you are doing this *after* your call to scanf ... – Levon Sep 09 '12 at 17:19