ansi c 意外行为有问题吗?
我正遭受一种意想不到的行为;这是问题定义:
我有应用程序通过 UDP 协议在 LAN 上进行通信。我正在从文本文件中读取 IP 地址和端口号。最初,IP 地址和端口号工作正常,但一段时间后,存储在 char 数组中的 IP 地址被损坏,并且采用垃圾值。另外,文件写入也受此影响。我的意思是 IP 数组中的值也写入由同一应用程序写入的文本文件中。我不明白出了什么问题 - 你能帮忙吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这几乎肯定意味着您有缓冲区溢出 - 甚至可能是堆栈溢出。您可能将太多字节读入太小的字节数组中,并且超出了分配空间的末尾并践踏了其他数据(例如 IP 地址)。
如果您使用的是 Linux,请考虑使用 valgrind 来帮助诊断问题。
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.
这很可能是由于访问某些数组的边界之外造成的。也可能是未初始化的指针问题。
如果您使用的是 Linux,请尝试在 valgrind 下运行您的程序。
确保所有数组都足够大。考虑添加
assert()
来检查数组索引是否正常以及类似的事情。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.如果您使用 memcpy() 复制数据,请检查您是否使用了正确的大小参数,或者如果您使用 strcpy() 确保将空终止字符串传递给 strcpy()
memcpy 的大小不正确或传递给 strcpy() 的末尾没有空字符的字符串将导致这些函数写入超出目标缓冲区的预期边界并导致内存损坏。
可能还有其他原因,例如终止条件不正确的循环等。
请将您的代码粘贴到此处,以便我们查看。
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.
就像其他人在这里提到的那样,如果您使用 Linux/UNIX 并且同时使用调试器,请使用 valgrind。尝试运行:
在第一次出现错误时,valgrind 将停止并提示您附加调试器。
几个常见的嫌疑人:
尝试使用 STL 字符串或crope,无论什么对你有用。
Like everyone else has mentioned here, use valgrind if you are Linux/UNIX and also use a debugger simultaneously. Try running with:
On the first instance of an error, valgrind will stop and prompt for you to attach the debugger.
Couple of usual suspects:
Try using STL strings or crope, whatever works for you.