Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in storage of memory in string and an integer array in C after using sprintf function

Tags:

c

Could you please explain me memory allocation in C for strings and integer array after using sprintf function?

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

int main() {
    char str[10];
    long long int i = 0, n = 7564368987643389, l;
    sprintf(str, "%lld", n);  // made it to a string 
    printf("%c%c", str[11], str[12]);
}

In the above code, string size is 10 inclusive of null character. How come we access 11 and 12 elements in it? The program prints 43


1 Answers

Here

sprintf(str,"%lld",n);

n i.e 7564368987643389 converted into character buffer & stored into str. It looks like

str[0]     str[2]   str[4]    str[6]     str[8]   str[10]   str[12] ..
--------------------------------------------------------------------------------------
| 7  | 5  | 6  | 4  | 3  | 6  | 8  | 9  | 8  | 7  | 6  | 4  | 3  | 3  | 8  | 9  | \0 |
--------------------------------------------------------------------------------------
str   str[1]    str[3]    str[5]    str[7]    str[9]    str[11] ..

As you can see str[11] is 4 and str[12] is 3. Hence the printf() statement below prints:

printf("%c %c",str[11],str[12]);

4 3

But since you have declared str of 10 characters and in sprintf() you are trying to store more than 10 characters, it causes undefined behavior.

like image 113
Achal Avatar answered Mar 21 '26 08:03

Achal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!