• Uncategorized

About c : C-program-crashing-because-of-invalid-address

Question Detail

I am not able to figure out why my program is crashing in the print statements. Pls help.

char *
infix_to_postfix(char *string, int str_len, int *new_len) {
*new_len = str_len;
return string;
fsm_t *
fsm_nfa_construction(char *string, int str_len) {
    int new_len;
    char *postfix_str = infix_to_postfix(string, str_len, &new_len);
    // return fsm_nfa_construction_internal(postfix_str, new_len);
    printf ("%s\n", postfix_str);
    return NULL;
main(int argc, char **argv) {
    char str[32];
    strncpy(str, "ab|*c.\0", strlen("ab|*c.\0"));
    fsm_t *fsm = fsm_nfa_construction(str, strlen(str));
    return 0;
(gdb) f 2
#2 0x0000555555556aa8 in fsm_nfa_construction (string=0x7fffffffdc20 "ab|*c.", str_len=6) at fsm.c:715
715 printf ("%s\n", postfix_str);
(gdb) p postfix_str
$3 = 0xffffffffffffdc20 <error: Cannot access memory at address 0xffffffffffffdc20>

Question Answer

Looks like a null terminator issue..

in this line:

strncpy(str, "ab|*c.\0", strlen("ab|*c.\0"));

due to the length returned by strlen, the null terminating character is not being copied into str. This is because strlen detects the length of a string by scanning until it finds a null character, which in this case is embedded in your string literal. To also copy the null terminating character, just add 1 like so:

strncpy(str, "ab|*c.\0", strlen("ab|*c.\0")+1);

Since str is not initialized, there is no guarantee that the data bytes there are zero’s (null terminating characters). The printf with the %s format specifier works by detecting the null terminating charater too. since there isn’t one in your buffer, the print never stops and crashes the program.

This isn’t related to your question, but I don’t think your support functions here are doing what you expect. For example, the infix_to_postfix function does not do anything useful. It just copies one integer to another and returns the same pointer passed in.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.