分段故障

Segmentation fault

我刚刚创建了一个程序,可以在缓冲区中找到命令。问题是当代码开始时,我总是立即收到分段错误。我什至尝试在 main 的开头放置一个 print 语句,但它仍然没有显示任何内容。

#include <stdio.h>
#include <stdlib.h>

void convertToUpperCase(char str[], int _size)
{
   int i = 0;
   while(i < _size)
   {
      str[i] = toupper(str[i]);
      i++;
   }
}

int CheckText(char command[],
              char buffer[],
              int starting_point,
              int size_of_buffer,
              int size_of_command)
{
   printf("%s", buffer);
   size_of_command--;
   convertToUpperCase(buffer, size_of_buffer);
   convertToUpperCase(command, size_of_command);

   int i = 0;
   int r = 0;
   while(i < size_of_command)
   {
      if(buffer[i+starting_point] == command[i])
      {
         r++;
         printf("%d", r);
      }
      i++;
   }

   int flag = 0;
   if(r == size_of_command)
   {
      flag = 1;
   }

   return flag;
}

int main()
{
   char h[40] = "hello";
   int fla;
   printf("hey1");
   fla=CheckText("hello", h,0,40,6);
   if(fla == 1)
   {
      printf("command recognized ");
   }
   //printf("%s\n", h);

   return 0;
}

正如@BLUEPIXY 所指出的,使用

CheckText("hello", h,0,40,6);

CheckText 修改其参数时会导致未定义的行为,因为 "hello" 位于代码的只读部分。使用类似:

char h[40] = "hello";
char h2[40] = "hello";
int fla;
printf("hey1");
fla=CheckText(h2, h,0,40,6);