shaggy
shaggy

Reputation: 651

Memory error with malloc

I always get either 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

Upvotes: 3

Views: 825

Answers (1)

lzap
lzap

Reputation: 17174

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;

Upvotes: 7

Related Questions