gcc 4.9.2 bug in -Werror=sizeof-pointer-memaccess?

You fell straight into the trap.

In C, C++, Objective-C, Objective-C++, a parameter with a declaration that looks like "array of T" actually has type T*.

Your parameter charArray has a declaration that looks like "array of 100 chars", but the declaration is in fact "pointer to char".

Therefore, your third parameter to strncpy has a value of (most likely) 4 or 8, and not the 100 that you seem to expecct.

BTW. strncpy is highly dangerous the way you use it.

link: https://stackoverflow.com/questions/29186056/gcc-4-9-2-bug-in-werror-sizeof-pointer-memaccess

下面的代码中警告是什么原因,怎么解决

memset(m_pBuffer,0,sizeof(m_pBuffer));

warning: argument to 'sizeof' in 'void* memset(void*, int, size_t)' call is the same expression as the destination; did you mean to provide an explicit length? [-Wsizeof-pointer-memaccess]
memset(m_pBuffer,0,sizeof(m_pBuffer));

首先,m_pBuffer应该是个成员指针变量,不是数组名吧。sizeof 运算符对“指针变量”运算的结果是指针变量的字节大小(32位4字节,64位8字节),可不是其指向的数据的大小哦。
对数组名运算是为数组分配的空间的字节大小。
其次,这个警告:**-Wsizeof-pointer-memaccess**

Warn for suspicious length parameters to certain string and memory built-in functions if the argument uses sizeof.
This warning warns e.g. about memset (ptr, 0, sizeof (ptr)); if ptr is not an array, but a pointer, and suggests a possible fix, or about memcpy (&foo, ptr, sizeof (&foo));. This warning is enabled by -Wall.
gcc编译器检测到可疑的使用sizeof对指针做了运算而不是数组,所以给了个温馨提示哦。

怎么解决:
对指针指向的数据做sizeof,如果是new分配的还要乘上数量了。

memset的最后一个参数是你m_pBuffer指向缓冲区的长度,而不是m_pBuffer指针的长度。sizeof(m_pBuffer)求出来一般是4,也就是指针的长度。

m_pBuffer是指针,sizeof(指针) == 4;sizeof(m_pBuffer) 改成 strlen(m_pBuffer);

m_pBuffer是数组还是指针,如果是指针,你后面的sizeof得到的是指针大小4,而不是整个存储空间的长度。

用strlen试一下,如果是char类型的,wchar就用_tcslen

link: https://stackoverflow.com/questions/1461432/what-is-array-decaying

https://stackoverflow.com/questions/19202368/snprintf-error-argument-to-sizeof-is-the-same-as-destination

你可能感兴趣的:(CPP)