Valgrind的警告:我应该把它当回事 [英] Valgrind Warning: Should I Take It Seriously

查看:154
本文介绍了Valgrind的警告:我应该把它当回事的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:
我有一个小程序,模仿与fgets(字符,2,FP),只不过它采用的字符从一个字符串,而不是流。 newBuff是动态分配的字符串作为参数传递和字符被声明为 CHAR字符[2]

Background: I have a small routine that mimics fgets(character, 2, fp) except it takes a character from a string instead of a stream. newBuff is dynamically allocated string passed as a parameter and character is declared as char character[2].

常规:

character[0] = newBuff[0];

character[1] = '\0';

strcpy(newBuff, newBuff+1);

,因为每个字符从它读出的的strcpy复制的信息的丢失。

The strcpy replicates the loss of information as each character is read from it.

问题:Valgrind的确实警告我有关
  本次活动,源和目标
  在的strcpy(重叠0x419b818,
  0x419b819)。

Problem: Valgrind does warns me about this activity, "Source and destination overlap in strcpy(0x419b818, 0x419b819)".

我应该担心这个警告?

推荐答案

大概标准没有规定当这些缓冲区重叠会发生什么。所以,是的,的valgrind 是正确的抱怨。

Probably the standard does not specify what happens when these buffers overlap. So yes, valgrind is right to complain about this.

在实践中,你很可能会发现, 的strcpy 为了拷贝由左到右(如而(* DST ++ = * SRC ++); ),它不是一个问题。但是,它仍然不正确,可与其它C库运行时有问题。

In practical terms you will most likely find that your strcpy copies in order from left-to-right (eg. while (*dst++ = *src++);) and that it's not an issue. But it it still incorrect and may have issues when running with other C libraries.

一个标准的正确的方式来写,这将是:

One standards-correct way to write this would be:

memmove(newBuff, newBuff+1, strlen(newBuff));

由于 memmove与定义来处理重叠。 (这里虽然你最终会遍历字符串两次,一次检查长度并一次复制。我还拿了一条捷径,因为的strlen(newBuff)应该等于的strlen(newBuff + 1)+1 ,这是我原来写的。)

Because memmove is defined to handle overlap. (Although here you would end up traversing the string twice, once to check the length and once to copy. I also took a shortcut, since strlen(newBuff) should equal strlen(newBuff+1)+1, which is what I originally wrote.)

这篇关于Valgrind的警告:我应该把它当回事的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆