confused
confused

Reputation: 31

second memcpy() attaches previous memcpy() array to it

I have a little problem here with memcpy()

When I write this

char ipA[15], ipB[15];
size_t b = 15;
memcpy(ipA,line+15,b);

It copies b bytes from array line starting at 15th element (fine, this is what i want)

memcpy(ipB,line+31,b);

This copies b bytes from line starting at 31st element, but it also attaches to it the result for previous command i.e ipA.

Why? ipB size is 15, so it shouldnt have enough space to copy anything else. whats happening here?

Where am I wrong? I dont actually know alot about memory allocation in C.

Upvotes: 2

Views: 305

Answers (3)

DrAl
DrAl

Reputation: 72726

It looks like you're not null-terminating the string in ipA. The compiler has put the two variables next to one another in memory, so string operations assume that the first null terminator is sometime after the second array (whenever the next 0 occurs in memory).

Try:

char ipA[16], ipB[16];
size_t b = 15;
memcpy(ipA,line+15,b);
ipA[15] = '\0';
memcpy(ipB,line+31,b);
ipB[15] = '\0';
printf("ipA: %s\nipB: %s\n", ipA, ipB)

This should confirm whether this is the problem. Obviously you could make the code a bit more elegant than my test code above. As an alternative to manually terminating, you could use printf("%.*s\n", b, ipA); or similar to force printf to print the correct number of characters.

Upvotes: 6

Didier Trosset
Didier Trosset

Reputation: 37477

Character strings in C require a terminating mark. It is the char value 0.

As your two character strings are contiguous in memory, if you don't terminate the first character string, then when reading it, you will continue until memory contains the end-of-string character.

Upvotes: 0

DarkDust
DarkDust

Reputation: 92414

Are you checking the content of the arrays by doing printf("%s", ipA) ? If so, you'll end up with the described effect since your array is interpreted as a C string which is not null terminated. Do this instead: printf("%.*s", sizeof(ipA), ipA)

Upvotes: 2

Related Questions