Memory error with malloc
I always get eith开发者_运维知识库er malloc() error. Here is the code:
char *data = malloc(200);
add_data(data, tableO, line);
void add_data(char *data, struct ARP_entryO *tableO, int line)
{
int i=0;
while (i < line)
{
strcat(data, tableO[i].IPaddr);
strcat(data, " ");
strcat(data, tableO[i].MACaddr);
strcat(data, " ");
i++;
}
}
I usualy send about 50-60bytes. Any help with this issue?
Thanks
It's because you dont reset the string to empty string. The malloc function just allocates some memory, you are concatenating strings, but with some "garbage". Sometimes you can receive empty string, sometimes not.
The solution is to store empty string there before your loop:
data[0] = '\0'; //or data[0] = 0; or data[0] = NULL;
精彩评论