Strange sscanf behavior with string

I have problems with sscanf. To test this, I made a simple file, so when I compile this:

#include <stdio.h>
main(){
    char *a;
    /* */
    char *s = "GET /something HTTP/1.1\r\n";
    printf("sscanf: %d\n", sscanf(s, "GET %s HTTP", a));
    printf("a: %s\n", a);
    /* */
    printf("sscan: %d\n", sscanf("GET /more HTTP/1.1\r\n", "GET %s HTTP", a));
    printf("a: %s\n", a);
}

I get the correct output:

sscanf: 1
a: /something
sscan: 1
a: /more

But when I comment out the lines between empty comments, I get:

sscan: 0
a: (null)

Question 1 : How can this be?

And a little more: if I write char *a = NULL, I get:

sscanf: 0
a: (null)
sscan: 0
a: (null)

Question 2 : Why?

0
source share
4 answers

You copy the string to an uninitialized pointer ( a). You need to allocate storage for it (using malloc) or declare an array.

, - . NULL a, sscanf , "" NULL ( printf (null)). .

/, , , , , .

char *a;
scanf("%ms", &a;) // allocates storage for a

, &.

+5

sscanf. char *a; char a[100], .

+2

. char *a; - . , "", undefined, .

0

, , , -, :

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

main(){
    char *s = strdup("GET /something HTTP/1.1\r\n");
    char *a, *e, *ans;
    char *end = s + strlen(s);
    a = strstr(s, "GET");
    if(!a) return -1;
    a += 4;
    if(a >= end) return -1;
    e = strstr(a, "HTTP/1.1");
    if(!e) return -1;
    *(--e) = 0;
    ans = strdup(a);
    printf("ans: %s\n", ans);
}

s , , , .

"% as" gcc (4.7.2).

0

All Articles