The program takes a pointer to a char
array and an int
. The char
array consists of two numbers, separated by a space.
The use of the function is to read the values of the char
array as integers and replace them with the multiplied value of the input:
void read_and_mul(char *arr, int scale) {
int num_arr[2]; // saving values in a int[]
char *ch = strtok(arr, " ");
num_arr[0] = scale * (atoi(ch));
ch = strtok(NULL, " ");
num_arr[1] = scale * (atoi(ch));
memset(arr, 0, sizeof(arr)); // deleting the previous value of the char[]
char one[sizeof(int)];
char two[sizeof(int)];
sprintf(one, "%d", num_arr[0]); // saving the altered numbers as chars
sprintf(two, "%d", num_arr[1]);
strcat(arr, one); // writing the multiplied values to the string
strcat(arr, " ");
strcat(arr, two);
}
However if I use it like this, it works as intended but causes a stack-smashing:
int main(int argc, char *argv[]) {
char str[] = "1 2";
read_and_mul((char *)&str, 10);
printf("string after call: %s\n", str);
return 0;
}
The terminal message in CLion is:
*** stack smashing detected ***: terminated
string after call: 10 20
Is this a potential error or an IDE warning and what is causing it?