roro
roro

Reputation: 131

Strange behavior with memcpy and "alias"

i'm dealing with memcpy to copy one array into another: here is the code, (i gave also the declarations)

.... /* s is a struct with int *t_con_cust;  */
/* bad to use an equivalent name i guess ..*/
s.t_con_cust = malloc(nb_cust*sizeof(*s.t_con_cust));
int *t_con_cust = malloc(nb_cust*sizeof(*t_con_cust));
...    
t_con_cust[0] = 1;
memcpy(s.t_con_cust, t_con_cust, nb_cust*sizeof(int));

fprintf(stdout, "s.t_con_cust[0] -> %d \n", s.t_con_cust[0]);
t_con_cust[0] = 0;
fprintf(stdout, "s.t_con_cust[0] -> %d \n", s.t_con_cust[0]);

The execution gave me :

s.t_con_cust[0] -> 1

s.t_con_cust[0] -> 0

which is beyond me, because when I tried with "sample code" like that

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct { 
    int *dest;
} lambda_struct;


int main(void) { 
    lambda_struct s;
    s.dest = malloc(10*sizeof(*s.dest)); 
    int *src  = malloc(10*sizeof(*src));
    int i;

    for(i = 0; i < 10; ++i) 
        src[i] = 1;

    memcpy(s.dest, src, 10);

    fprintf(stdout, "dest[0] -> %d \n", s.dest[0]);
    src[0] = 0;
    fprintf(stdout, "dest[0] -> %d \n", s.dest[0]);

    free(src);
    free(s.dest);

    return 0;
}

The execution give me the expected result, -> 1 and 1.

Any ideas ? Thanks

Upvotes: 2

Views: 148

Answers (1)

David Heffernan
David Heffernan

Reputation: 613302

If this code

fprintf(stdout, "s.t_con_cust[0] -> %d \n", s.t_con_cust[0]);
t_con_cust[0] = 0;
fprintf(stdout, "s.t_con_cust[0] -> %d \n", s.t_con_cust[0]);

results in

s.t_con_cust[0] -> 1
s.t_con_cust[0] -> 0

then the only explanation that makes sense is that

t_con_cust == s.t_con_cust

If that condition was not true then how could assignment to t_con_cust[0] affect s.t_con_cust[0]?

I predict that when you test the two pointers for equality you will find that they are indeed equal. And then you just need to find the part of the code that assigns the two pointers to the same value.

Upvotes: 2

Related Questions