You're not allocating any memory for ddj
. Since it's a local variable, it's allocated on the stack. Local variables are not initialized to 0/false/NULL by default, so the value of ddj
immediately after it's declared is undefined -- it will have the value of whatever is left in memory at that particular location on the stack. Any attempt to dereference it (that is, to read or write the memory at which it's pointing) will have undefined behavior. In your case, it's crashing because it's pointing to an invalid address.
To fix the problem, you need to allocate storage for ddj
. You can either allocate static storage on the stack, or dynamic storage on the heap. To allocate static storage, do:
// Allocate 64 bytes for ddj. It will automatically be deallocated when the function
// returns. Be careful of buffer overflows!
char ddj[64];
To allocate dynamic storage:
// Allocate 64 bytes for ddj. It will NOT be automatically deallocated -- you must
// explicitly deallocate it yourself at some point in the future when you're done
// with it. Be careful of buffer overflows!
char *ddj = new char[64];
...
delete [] ddj; // Deallocate it
Instead of managing storage yourself, it would be a better idea to use std::string
, which automatically deals with memory management.
Finally, since all you're doing is comparing the first three characters of the string, there's no need to jump through hoop to copy the string and compare it. Just use strncmp()
:
if(strncmp(buffer, "JMX", 3) == 0)
{
...
}