views:

94

answers:

4

I am suffering from an unexpected behavior; here is the problem definition:

I have applications communicating on a LAN via UDP protocol. I am reading the IP address and port number from a text file. Initially the IP address and port number are working nicely but, after some time, the IP address that is stored in a char array is corrupted and it takes garbage values. Also, the file writing is effected by this. I mean the values that are in the IP array are also written in text file that is written by the same application. I can't understand what is the problem - can you help?

+7  A: 

This almost certainly means you have a buffer overflow - possibly even a stack overflow. You are probably reading too many bytes into too small an array of bytes, and running past the end of the allocated space and trampling over your other data (such as the IP address).

If you are using Linux, consider using valgrind to help diagnose the problem.

Jonathan Leffler
Your comment is so similar to mine it is almost uncanny. ;)
Artelius
+7  A: 

This is most probably due to accessing outside the bounds of some array. It's also possible to be an uninitialised pointer problem.

If you're on Linux, try running your program under valgrind. Make sure all your arrays are large enough. Consider adding assert()s to check your array indices are OK and that kind of thing.

Artelius
Your answer is so similar to mine it is almost uncanny.
Jonathan Leffler
A: 

if you are using memcpy() to copy data, check whether you are using the correct size parameter or if you are using strcpy() make sure you are passing a null terminated string to strcpy() Incorrect size to memcpy or a string without null char at the end passed to strcpy() is going to cause these functions to write beyond the intended boundary of destination buffer and cause memory corruption. There may be other causes e.g. a loop with incorrect termination condition etc. Please paste your code here so that we can have a look.

Rohin
A: 

Like everyone else has mentioned here, use valgrind if you are Linux/UNIX and also use a debugger simultaneously. Try running with:

valgrind --db-attach=yes --db-command=</path/to/gdb -nw %f %p>

On the first instance of an error, valgrind will stop and prompt for you to attach the debugger.

Couple of usual suspects:

  1. Check if you are using fixed size arrays. Stuff like char buf[128]; may look cute but are worse than stuffed squirrel
  2. No gets() and puts() system calls please, in the name of the Lord

Try using STL strings or crope, whatever works for you.

Fanatic23