user3825136 user3825136 - 3 months ago 8
C Question

Having issues when printing an array of chars?

Since I don't really understand the overall issue I am having, it's become very difficult to debug.

char *o_key_pad = (char*)malloc(SHA256_DIGEST_LENGTH*sizeof(char));
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++){
o_key_pad[i] = 'a';
}
printf("%s\n", o_key_pad);

char *i_key_pad = (char*)malloc(SHA256_DIGEST_LENGTH*sizeof(char));
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++){
i_key_pad[i] = 'b';
}

printf("%s\n", o_key_pad);
printf("%s\n", i_key_pad);


And i obtain outputs:

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb


Why does the array 'o_key_pad' get extended to include whatever i put in array 'i_key_pad', seems like some sort of memory issue?

Note: I understand that it can be done more effectively but to show my point more clearly I have laid it out like this.

Answer

printf doesn't know where to stop unless you properly null-terminate your strings. C-style strings are as follows (the following two lines are equivalent; writing a string in quotes [a "string literal"] automatically creates a null-terminated character array):

char str[] = "hello world";
char str2[] = { 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '\0' };

This is what your code should look like:

int i;
char *o_key_pad = malloc(SHA256_DIGEST_LENGTH * sizeof (char) + 1);
for (i = 0; i < SHA256_DIGEST_LENGTH; ++i) {
    o_key_pad[i] = 'a';
}
o_key_pad[i] = '\0';
printf("%s\n", o_key_pad);

char *i_key_pad = malloc(SHA256_DIGEST_LENGTH * sizeof (char) + 1);
for (i = 0; i < SHA256_DIGEST_LENGTH; ++i) {
    i_key_pad[i] = 'b';
}
i_key_pad[i] = '\0';

printf("%s\n", o_key_pad);
printf("%s\n", i_key_pad);

/* Don't forget to free when done. */
free(o_key_pad);
free(i_key pad);