0

My initial idea for the credit problem was to convert the long from get_long into a char array, in order to obtain something iterable to get each digit for Luhn's algo.

I recognize that this could be achieved using modulo instead without having to convert the long.

However, I am wondering why this code does not result in a buffer overflow.

#include <cs50.h>
#include <stdio.h>

#define DIGIT 4     /* max digit length for any credit card */

int main (void) {
    // prompt user for number
    long n = get_long("Number: ");

    // verify Luhn's checksum algo

    // convert long to string for enumerating char array
    char str[DIGIT];
    sprintf(str, "%lu", n);
    int len = snprintf(NULL, 0, "%s", str);
    printf("%d", len);
    printf("%s", str);
}

Originally, the DIGIT constant was set to 16, but I was testing and now am confused as to why sprintf does not result in a buffer overflow when I input a number with more than 4 digits, ie

Number: 12345
5
12345
0

A buffer overflow can be silent. It sometimes leads to a segfault, and sometimes overwrites important data. Other times it's benign, existing in code for years without causing problems. Try declaring another string which is initialized in the declaration. This prints 'abc' for strB to start, but shows the buffer overflow after str is assigned.

#include <cs50.h>
#include <stdio.h>

#define DIGIT 4     /* max digit length for any credit card */

int main (void) {
    // prompt user for number
    long n = get_long("Number: ");

    // verify Luhn's checksum algo

    // convert long to string for enumerating char array
    char strB[DIGIT] = "abc\0";
    char str[DIGIT];
    printf("%s\n", strB);
    sprintf(str, "%lu", n);
    int len = snprintf(NULL, 0, "%s", str);
    printf("%d\n", len);
    printf("%s\n", str);
    printf("%s\n", strB);
}
2
  • I see, thank you. I had mistakenly assumed C would throw an error or exception when encountering a buffer overflow, if data went past the alloted instantiated array boundaries. Didn't realize it would just write past the boundary to another's address.
    – phomein
    Mar 29 at 2:39
  • In c++ the std lib has a "safe array" which does include bounds checking.
    – juls
    Mar 29 at 23:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .