This piece of code swap the first and last element of a given array:
#include <stdio.h>
/* swap first and last element of array */
void fn(void *v, size_t length, size_t size)
{
char *a = (char *)v;
char *b = (char *)v + size * (length - 1);
char temp;
do {
temp = *a;
*a++ = *b;
*b++ = temp;
} while (--size > 0);
}
int main(void)
{
int a[] = {0, 1, 2};
double b[] = {0., 1., 2.};
char c[][15] = {"Hello", ",", "this is a test"};
fn(a, 3, sizeof(a[0]));
fn(b, 3, sizeof(b[0]));
fn(c, 3, sizeof(c[0]));
printf("%d %d\n", a[0], a[2]);
printf("%f %f\n", b[0], b[2]);
printf("%s %s\n", c[0], c[2]);
return 0;
}
Output:
2 0
2.000000 0.000000
this is a test Hello
My question is:
The code is safe?, it is guaranteed that c[0] is initialized by the compiler as
{'h', 'e', 'l', 'l', 'o', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
or c[0] may contain {'h', 'e', 'l', 'l', 'o', 0, [garbage]}?
EDIT:
And if c is not initialized?
int main(void)
{
char c[3][15];
strcpy(c[0], "Hello");
strcpy(c[1], ",");
strcpy(c[2], "this is a test");
fn(c, 3, sizeof(c[0]));
printf("%s %s\n", c[0], c[2]);
return 0;
}
Is it safe to use fn? (c[0] contains 9 bytes of garbage)
fn()provokes UB forc's 1st and 2nd element.fn()byqsort()in EDIT'smain(). I would have never have thought about that (and to be honest, I still wouldn't be too afraid if I saw it tomorrow in my code)