I have been writing a function for extract information between each two newline characters.I am facing a problem when copying the char array 'data' to an element of 'info' array.
#include <stdio.h>
#include <string.h>
void query_db();
char buffer[100]="+HTTPREAD:86\nUdara\nNO\n+94123456789\nOK";
volatile int buffer_pointer;
char info[3][20];
int main()
{
query_db();
return 0;
}
void query_db(){
unsigned char j=0,start,end,amount;
char data[20];
buffer_pointer = 0;
while( buffer_pointer < strlen(buffer)){
if(buffer[buffer_pointer] == 10){
if(j==0){
start = buffer_pointer+1;
printf("headstart = %u\n",start);
}
else{
printf("\n%u start = %u\n",j,start);
end = buffer_pointer;
amount = end - start;
strncpy(data, buffer+start,amount);
memcpy(info[j-1],data,strlen(data));//need help in this line
printf("data = %s\n",info[j-1][20]);
memset(data,0,20);
start = end+1;
printf("%u end = %u\n",j,end);
}
j++;
}
buffer_pointer++;
}
}
When I execute above code , it gives following output instead of what I expected.
headstart = 13
1 start = 13
data = (null)
1 end = 18
2 start = 19
data = (null)
2 end = 21
3 start = 22
data = (null)
3 end = 34
Preferred output:
headstart = 13
1 start = 13
data = Udara
1 end = 18
2 start = 19
data = NO
2 end = 21
3 start = 22
data = +94123456789
3 end = 34
strncpywill not null-terminate the destination string. If that happens then usingstrlen(data)will lead to undefined behavior.void query_db();should have avoidbetween the parens. Otherwise, the compiler will produce code that can take any number of parameters Suggest the prototype be;void query_db( void );gcc, at a minimum use:-Wall -Wextra -Wconversion -pedantic -std=gnu11) Note: other compilers use different options to produce the same thingif(buffer[buffer_pointer] == 10){might never be 'true' Suggest using:if(buffer[buffer_pointer] == '\n' ){while( buffer_pointer < strlen(buffer)){the variablebuffer_pointer, (which is actually an index into the buffer, not a pointer) is comparing aintwith asize_t(asize_tis along unsigned int. Your compiler should have told you about this problem