Emre Erişgen Emre Erişgen - 3 months ago 10
C Question

C Sprintf Format Error

I'm trying to format the given string and printf it. Bu it doesnt work. It gives error Any idea?

char* query_buffer;

sprintf(query_buffer,"%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x;%u.%u.%u.%u;%d\n",
node_config->mac_address.addr[0], node_config->mac_address.addr[1], node_config->mac_address.addr[2], node_config->mac_address.addr[3],
node_config->mac_address.addr[4], node_config->mac_address.addr[5], node_config->mac_address.addr[6], node_config->mac_address.addr[7],
ip64_addr->u8[0], ip64_addr->u8[1], ip64_addr->u8[2], ip64_addr->u8[3],
node_config->coap_port);

printf("%s\n",query_buffer);


If I try below printf it works. I couldnt understand what is different between doing these two.

printf("%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x;%u.%u.%u.%u;%d\n",
node_config->mac_address.addr[0], node_config->mac_address.addr[1], node_config->mac_address.addr[2], node_config->mac_address.addr[3],
node_config->mac_address.addr[4], node_config->mac_address.addr[5], node_config->mac_address.addr[6], node_config->mac_address.addr[7],
ip64_addr->u8[0], ip64_addr->u8[1], ip64_addr->u8[2], ip64_addr->u8[3],
node_config->coap_port);

Answer

The line char* query_buffer; declares a pointer to a char but it the memory it points to might not be declared. So you can get a segmentation fault when you call sprintf to access that memory. Try declaring query_buffer like char *query_buffer = (char*)malloc(256);. That will create a pointer and declare 256 bytes at where it points to.

Comments