views:

153

answers:

3

Hi

The following code fragment ends in an exception when executing the strncpy funtion:

#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...

+5  A: 

You haven't allocated space for the destination buffer and fileName is uninitialized. 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

*(buffer + N) = 0;
sharptooth
A: 

You haven't allocated space for filename. Either do

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

or

filename = strndup (filestructure->name, MAX_FILENAME_LEN);
Lliane
malloc?? in a C++ application. please just use new
Glen
+1  A: 

Your question is tagged C++ but the code is pure C. Why do you do it the hard way? 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.

If you're writing C++, do it the C++ way. Use std::string. Honestly, it will spare you many hours of debugging such code.

sbi