简体   繁体   English

使用strncpy时发生异常

[英]Exception when using strncpy

The following code fragment ends in an exception when executing the strncpy function: 在执行strncpy函数时,以下代码片段以异常结尾:

#define MAX_FILENAME_LEN 127

typedef struct {
unsigned long nameLength;
char name[MAX_FILENAME_LEN + 1];
} filestructure;

char *fileName;

strncpy( fileName, filestructure->name, MAX_FILENAME_LEN );
*( fileName + MAX_FILENAME_LEN+1 ) = 0; 

Ayone an idea what could go wrong? 知道会有什么问题吗? In the filestructure I have a filename that is 50 characters long so it is within the bounds... I am really a bit lost what could cause the problem in this simple code fragement... 在文件结构中,我的文件名长度为50个字符,因此它在范围之内...我确实有点丢失了什么,这可能会导致这种简单的代码断裂问题。

You haven't allocated space for the destination buffer and fileName is uninitialized. 您尚未为目标缓冲区分配空间,并且fileName未初始化。 So you try to copy somewhere . 因此,您尝试在某处复制。 You should allocate memory and then bother freeing it. 您应该分配内存,然后再释放它。

char *fileName = new char[MAX_FILENAME_LEN + 1];
strncpy(...);
*(...) = 0;
doStuffWithTheBuffer( fileName );
delete[] fileName;// free memory

Also if you have a buffer of size N + 1 and want to copy N bytes maximum and null-terminate the buffer you should do 另外,如果您有一个大小为N + 1的缓冲区,并且想复制最多N个字节并以null终止缓冲区,则应该执行此操作

*(buffer + N) = 0;

Your question is tagged C++ but the code is pure C. Why do you do it the hard way? 您的问题被标记为C ++,但是代码是纯C的。为什么要用困难的方式呢? The fact that C string handling isn't all that easy to grasp (and that it isn't all that uncommon to get something wrong once in a while even for programmers who have a good grasp of it) is the very reason C++ let's you do without. C字符串处理并不是那么容易掌握的事实(即使对于精通它的程序员来说,偶尔出错也并非罕见)是C ++助您一臂之力的原因。没有。

If you're writing C++, do it the C++ way. 如果您正在编写C ++,请以C ++方式进行。 Use std::string . 使用std::string Honestly, it will spare you many hours of debugging such code. 老实说,它将为您节省许多调试此类代码的时间。

You haven't allocated space for filename. 您尚未为文件名分配空间。 Either do 要么做

filename = malloc (MAX_FILENAME_LEN * sizeof(char));

or 要么

filename = strndup (filestructure->name, MAX_FILENAME_LEN);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM