-1

I am performing sprintf on a char array of size 1 and the code works fine. i.e strlen returns 1 even though it may not be null terminated. To my understanding sprintf will do null termination, however in this case it does not have enough space. Can someone explain the reason it works?

#include <stdio.h>
#include <string.h>
#define STATUS "1"
int main(void){
    char *data = malloc(1);
    sprintf(data, "%s", STATUS);
    printf(">%s<\n", data);
    printf(">%d<\n", strlen(data));
}

Output

>1<
>1<
Zac
  • 162
  • 2
  • 10
  • 1
    Basically the program hits undefined behaviour. Which means any behaviour can occur, including sometimes working. But it may fail the next time it is run, or if run on a different machine, etc. – kaylum Dec 01 '19 at 11:05
  • 1
    The reason it works is probably because `malloc` gave you something more than 1 byte. But formally that memory is not yours and can result in UB. – Paul Ogilvie Dec 01 '19 at 11:26

2 Answers2

2

The program has undefined behavior.

It works because in general malloc allocates memory chunks multiple by the paragraph size equal to 16 or some other implementation defined value.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

You want snprintf()

if (snprintf(data, SIZE, "%s", STATUS) >= SIZE) /* not enough space */;

#include <stdio.h>

int main(void) {
    char buf[10];
    for (int k = 0; k < 6; k++) {
        int res = snprintf(buf, k, "%s", "foo");
        printf("%d: snprintf() returned %d; buf has [%s] (%d chars)\n",
              k, res, buf, (int)strlen(buf));
    }
    return 0;
}

And that program outputs

0: snprintf() returned 3; buf has [] (0 chars)
1: snprintf() returned 3; buf has [] (0 chars)
2: snprintf() returned 3; buf has [f] (1 chars)
3: snprintf() returned 3; buf has [fo] (2 chars)
4: snprintf() returned 3; buf has [foo] (3 chars)
5: snprintf() returned 3; buf has [foo] (3 chars)

See ideone

pmg
  • 106,608
  • 13
  • 126
  • 198
  • What happens when buf does not have enough space? – Zac Dec 01 '19 at 11:29
  • You cannot call `snprintf(buf, size, ...)` with `size` greater than the space available in buf!!! If you do so you invoke UB ... and bad things happen. Usually we see something like: `snprintf(buf, sizeof buf, ...)` – pmg Dec 01 '19 at 11:53