0

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

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

BenMorel
  • 34,448
  • 50
  • 182
  • 322
  • 2
    Use std::string unless you have a really good reason not too. – Chris Huang-Leaver Aug 14 '09 at 12:39
  • 1
    "An exception"? You are using a C function, and C does not have exceptions. In any case, it sometimes helps, when asking about errors you encounter, to *describe the error*. *Which* exception did you get? – jalf Aug 14 '09 at 12:40
  • @jalf: It's probably an OS exception, likely an Access Violation. – sbi Aug 14 '09 at 12:42
  • Funny how this code looks pretty much like a copy of the first answer in http://stackoverflow.com/questions/1265117/structure-problem-in-c/1265196#1265196 asked by some 'Claus'. I suspect 'Robert' and 'Claus' are the same person. – Frerich Raabe Aug 14 '09 at 12:54

3 Answers3

5

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
  • 167,383
  • 100
  • 513
  • 979
1

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
  • 219,715
  • 46
  • 258
  • 445
0

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
  • 831
  • 2
  • 7
  • 15