when used %u in sprintf() application gets crashed, it's working fine %d
see code:
#include <stdio.h> #include <string.h> main() { unsigned char daddr[4]; unsigned char smask[4]; unsigned char nhop[4]; memset(daddr,0,sizeof(daddr)); memset(smask,0,sizeof(smask)); memset(nhop,0,sizeof(nhop)); unsigned int u4ipdaddr = 0x01020304; unsigned int u4ipsnetmask = 0xffff01ff; unsigned int u4nhopgt = 0x01020304; char *dip = (char *)&u4ipdaddr; char *smk = (char *)&u4ipsnetmask; char *nhp = (char *)&u4nhopgt; sprintf(daddr, "%u.%u.%u.%u", dip[3], dip[2], dip[1], dip[0]); //if used %d.%d.%d.%d working fine sprintf(smask, "%u.%u.%u.%u", smk[3], smk[2], smk[1], smk[0]); //if used %d.%d.%d.%d working fine sprintf(nhop, "%u.%u.%u.%u", nhp[3], nhp[2], nhp[1], nhp[0]); //if used %d.%d.%d.%d working fine printf("sam: func %s line %d ipdaddr %s mask %s nhop %s\n",__func__,__line__,daddr,smask,nhop); } when declared pointer's following manner working fine %u.%u.%u.%u format
unsigned char *dip = (unsigned char *)&u4ipdaddr; unsigned char *smk = (unsigned char *)&u4ipsnetmask; unsigned char *nhp = (unsigned char *)&u4nhopgt; can 1 explain happening when used char pointers?
in case
unsigned char daddr[4]; unsigned char smask[4]; unsigned char nhop[4]; are not sufficient hold lexicographical output.
when you're using arrays destination string in sprintf(), essentially, you're overrunning allocated memory, creating undefined behaviour.
you need allocate more memory use arrays destination of sprintf().
Comments
Post a Comment