what is stack smashing (C)?

后端 未结 2 1847
-上瘾入骨i
-上瘾入骨i 2021-02-09 22:00

Code:

int str_join(char *a,  const char *b) {
   int sz =0; 
   while(*a++) sz++;  
   char *st = a -1, c;  
   *st = (char) 32;
   while((c = *b++)) *++st = c;           


        
2条回答
  •  遥遥无期
    2021-02-09 22:18

    Well, stack smashing or stack buffer overflow is a rather detailed topic to be discussed here, you can refer to this wiki article for more info.

    Coming to the code shown here, the problem is, your array a is not large enough to hold the final concatenated result.

    Thereby, by saying

     while((c = *b++)) *++st = c;
    

    you're essentially accessing out of bound memory which invokes undefined behavior. This is the reason you're getting the "stack smashing" issue because you're trying to access memory which does not belong to your process.

    To solve this, you need to make sure that array a contains enough space to hold both the first and second string concatenated together. You have to provide a larger destination array, in short.

提交回复
热议问题