开发者

Memory error with malloc

开发者 https://www.devze.com 2023-03-21 19:38 出处:网络
I always get eith开发者_运维知识库er malloc() error. Here is the code: char *data = malloc(200);

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;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号