3

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

2
  • 1
    the error is most probably not on malloc(). Most likely you are going past table0 bounds Commented Jul 21, 2011 at 13:05
  • 1
    if your going to allocate memory like that at a global scope, you may as well just do char data[200]; Commented Jul 21, 2011 at 13:09

1 Answer 1

7

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; 
Sign up to request clarification or add additional context in comments.

5 Comments

Something like strcpy(data, "") or *data[0] = 0 (not sure about the C syntax - its like 15 years ago I was programming in C for the last time :-)
@Izap: My point is that strcat expects a null terminated string as its arhument. So setting first char as 0 is enough for it to think it's an empty string.
Yeah, so the syntax of the second solution is what Armen propose. Without the "*" character. :-) Good luck!
@Armen - thanks for providing the correct C/C++ syntax. I am really not sure how pointer works after years :-)
It is not working. Is it possible that as I always terminate the program with ctrl+c, there is still some process running, and as I run the program again, this results in this error? Im not really Programming/Linux guy, just trying to guess

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.