Reputation: 18242
I have the following:
//MTU = 1472 | numBytes = 5000
/*char* data =
#################################################
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
#################################################
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
#################################################
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
*/
char* payload = NULL;
size_t packetSize;
(numBytes > MTU) ? packetSize = MTU : packetSize = numBytes;
memcpy(payload, data, packetSize);
Whenever I try to do memcpy
to copy the first 1472
bytes from data
to payload
, I get a segfault - any hints why?
Upvotes: 0
Views: 115
Reputation: 141574
payload
is NULL
so you cause undefined behaviour if you try to memcpy
to it. Where do you think those bytes are going?
You have to allocate space to write it. For example:
payload = malloc(packetSize);
if ( !payload )
{ exit(EXIT_FAILURE); /* error handling */ }
memcpy(payload, data, packetSize);
// ...use payload...
free(payload);
Also you should check that data
actually has as much data in it as packetSize
. If you write char const data[] = ".....";
then you can use sizeof data - 1
to check this.
Upvotes: 3
Reputation: 6777
You never initialize payload
:
char* payload = NULL; // payload null
size_t packetSize;
(numBytes > MTU) ? packetSize = MTU : packetSize = numBytes;
memcpy(payload, data, packetSize); // copy data to null address ... segfault
Instead you'll need to malloc
or new
:
char* payload = new char[packetSize];
or
char* payload = (char*)malloc(packetSize);
... don't forget to delete[]
/free
Upvotes: 4
Reputation: 223013
Because you're trying to copy stuff to a null pointer. That's not the valid location of a buffer.
Upvotes: 2