I am trying to parse the following "incoming_message" to different variables and the code works perfectly until the function ends. Then I get the following error: "Run-Time Check Failure #2 - Stack around the variable 'network_number' was corrupted."
This is the code where I am getting the error:
char* incoming_message = "\r\n+COPS: (2,\"MOVISTAR\",,\"12345\"),(1,\"AMENA\",,\"12346\"),(1,\"E AIRTEL\",,\"12347\"),,(0-4),(0,2)\r\n";
int stat;
char network_name[16];
char network_number[6];
char processed_message[128];
const char* pch_msg = "%d, %[^,],, %[^')']";
// I introduce spaces to remove the inverted commas
for(int i=2; i < strlen(incoming_message); i++)
{
if (incoming_message [i] == '"')
{
processed_message[i] = ' ';
}
else
{
processed_message[i] = incoming_message [i];
}
}
for(int i=2; (incoming_message[i]!='\r') || i < strlen(incoming_message); i++)
{
if(incoming_message[i] == '(')
{
i++;
int const sscanf_res = sscanf(&processed_message[i], pch_msg, &stat, &network_name, &network_number);
if (sscanf_res != 3)
{
break;
}
}
}
}
Does somebody have any idea why I am getting this error? Is there any other way to do it more simple?
Thanks in advance!
As the name suggests, this error occurs when you write more characters than the allocated space. In this case, you are writing 7 characters to an array having space for 6 characters.