Question

I am using memcpy function in my code and getting Segmentation Fault error when i run it. Following goes the code.

memcpy ((void *) ((unsigned int) core_data + (width * height * bpp)), (void *) core_data, (width * height * bpp));

core_data is unsigned short pointer and height, width and bpp are static int type. The value of (width * height * bpp) is 8355840. When i reduce this value, to say 10, the error is resolved. But in real case scenario i have to keep the value to 8355840. any solution ?

thanks

Was it helpful?

Solution

Please show more code.

Your use of casts is very strange, and there's too many parentheses in there to make it readable. You should rarely cast pointers to integers, and if you do you must use e.g. intptr_t to make sure that the integer is large enough to hold the pointer value (the number of bits in unsigned int might be smaller than the number of bits in unsigned short *), else the pointer is destroyed when casting.

It should just be:

memcpy(core_data + width * height * bpp, core_data, width * height * bpp);

Pointer arithmetic in C is a (very good) thing, you don't need to cast to/from integers just to compute addresses. Remember that pointer arithmetic is "scaled" by the size of the pointed-to objects, which might mean that bpp should just be 1 if core_data is a pointer to 16-bit integers and your pixels are 16-bit.

Also, of course, make sure that the memory is properly allocated, i.e. that you do:

core_data = malloc(2 * width * height * bpp * sizeof *core_data);

and have it return non-NULL.

Of course, we can further boost the niceness of this code by factoring out the size of one "frame":

const size_t frame_size = width * height * bpp;

Then we can use this wherever needed, to make it more clear what's going on:

core_data = malloc(2 * frame_size);

and:

memcpy(core_data + frame_size, core_data, frame_size);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top