Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying arrays in C

Tags:

arrays

c

In my C program I am trying to copy an array of char's to another array whilst removing the first element (element 0).

I have written:

char array1[9];
char array2[8];
int i, j;

for(i = 1, j = 0 ; i < 10, j < 9; i++, j++){
        array2[j] = array1[i];
}
printf(array2);

When I print array2, it gives me a stack overflow.

Any ideas?

like image 663
Stuart Avatar asked Nov 27 '25 20:11

Stuart


2 Answers

Use memcpy():

memcpy( array2, &array1[1], 8 );

Thats easier.

like image 153
onemasse Avatar answered Nov 30 '25 09:11

onemasse


Two issues: First, when printing a string with printf, and working with other standard C string functions in general, your char arrays need to be null-terminated so the functions know where the string ends. You are also writing one past the end of your arrays.

Second, when using printf, it is almost always a bad idea to use the string you want to print as the format string. Use

printf("%s", array2);

instead. If you use printf as in the original example and array2 can be influenced by the user, then your program is likely vulnerable to a format string vulnerability.

like image 27
user470379 Avatar answered Nov 30 '25 10:11

user470379



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!