Question

Im facing with a "memory fault" when calling to:

extern void *memcpy (void *__restrict __dest,
         __const void *__restrict __src, size_t __n)
 __THROW __nonnull ((1, 2));

This is the piece of code:

    fprintf(stderr, "sysconfig line 440 \n");
fprintf(stderr, "Value size: %d ; Pointer mymsg: %p ; Pointer value: %p ; mymsg->mtext: %s ; value: %s ; size: %d ;   \n", strlen(value), mymsg, value, mymsg->mtext, value, size);
memcpy(mymsg->mtext, value, size);
fprintf(stderr, "sysconfig line 442 \n");

mymsg is a pointer to struct:

MSG_T *mymsg;

MSG_T:

typedef struct msgInfo {
int cmd;
int arg1;
int arg2;
char    mtext[MAX_SEND_SIZE];
} MSG_T;

MAX_SEND_SIZE = 4096, value is a (void *)char *string containing "" (\0 or empty chain) and size = 4096, so i dont understand why im getting a memory fault. Im checking there is not memory overlapping. This is the output of execution:

sysconfig line 440 
Value size: 0 ; Pointer mymsg: 0x7fd49ac4 ; Pointer value: 0x7fd4ab4c ; mymsg->mtext:      ; value:  ; size: 4096 ;   
Memory fault

I have not found What kind of condition here can result in segmentation since all memory has been well allocated, value is a empty string and there is no memory overlapping.

I only get memory fault sometimes (it seems randomly) and other times the process follow executing and exit with no errors.

Was it helpful?

Solution

memcpy(mymsg->mtext, value, size);

value is a string of length 0 and you are trying to copy 4096 bytes from this string. You are therefore accessing 4095 unallocated bytes which means you are invoking undefined behavior.

OTHER TIPS

You mentioned that value is a (void *)char *string containing "". but size argument for memcpy is 4096, that is the probelm.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top