I was faced with a simple task in a given line to insert some
the number of spaces between words so that the line length is 60 characters. But
at startup, the error “stack around the variable ‘s’ was corrupted” is displayed.
Who can tell you what the problem is?
#include "stdafx.h"
# include & lt; iostream & gt;
# include & lt; string.h & gt;
using namespace std;
void change (char arr [61] [130], char s [61], int i) {
int k = 0;
while (strlen (s) & lt; 60) {
if (k == i - 1) k = 0;
strcat_s (arr [k], sizeof arr [k], "");
memset (s, 0, sizeof (s));
for (int j = 0; j & lt; i; j ++)
strcat_s (s, sizeof arr [j], arr [j]);
k ++;
}
printf ("% s", "A new string:");
printf ("% s \ n", s);
}
void break_on_array (char s [61]) {
char * p;
char * np = NULL;
char * delim = "";
int i = 0;
char arr [61] [130];
p = strtok_s (s, delim, & amp; np);
while (p! = NULL) {
strcpy_s (arr [i], sizeof arr [i], p);
p = strtok_s (NULL, delim, & amp; np);
i ++;
}
change (arr, s, i);
}
int main ()
{
setlocale (LC_ALL, "rus");
char s [61];
printf ("% s \ n", "Enter a string:");
gets_s (s);
break_on_array (s);
return 0;
}
Answer 1, authority 100%
The debug version of the strcat_s
function fills the unused remainder of the buffer with the value 0xFD
on each call, up to the specified size
https://msdn.microsoft.com/en-us/library /d45bbxx4.aspx
The debug versions of these functions first fill the buffer with 0xFD. To disable this behavior, use _CrtSetDebugFillThreshold.
Therefore, if you “lie” to the strcat_s
function about the size of your buffer, the value 0xFD
will be written out of the buffer, even if the strings you concatenate fit perfectly into target buffer.
In your code, you are obviously “lying” about the size of your buffer: the buffer size is 61
, and you pass the value sizeof arr [j] to
, i.e. strcat_s
130
. The first call to strcat_s
destroys the contents of the stack outside of s
, no matter what your input is.
This behavior of strcat_s
is done specifically in order to detect errors like yours as early as possible.
That’s all.
PS If you make _CrtSetDebugFillThreshold (0);
at the beginning of your program, then the error will “disappear”, because the actual buffer overflow in your code (with a “reasonable “input) does not occur. However, this, of course, is a profanation. If you are already using the functions of the _s
group, then use them correctly.
PPS Inside the change
function, the s
variable is of type char *
and, accordingly, sizeof ( s)
is just the size of the pointer. Therefore your
memset (s, 0, sizeof (s));
is a pretty pointless action. This “works”, but you could just as easily have done * s = 0
. Using memset
does nothing here.
Answer 2
Look closely at the syntax gets_s
char * gets_s (char * str, rsize_t n);
there are two parameters, not one. Therefore, you need to call at least this way
gets_s (s, 60);