简体   繁体   English

字符字符串参考上的分段错误

[英]Segmentation fault on char string reference

I have a small C++ function which reverses a string in place: 我有一个小的C ++函数,它可以在原处反转字符串:

void reverse1(string& s, int start, int end) {
  if (s.empty()) return;
  char tmp;

  while (start < end) {
    tmp = s[end];
    s[end] = s[start];
    s[start] = tmp;
    ++start;
    --end;
  }
}

This function works fine. 此功能工作正常。 However, when I rewrite it in c as below, I came across a segment fault on statement 11. 但是,当我按以下方式在c中重写它时,我在语句11上遇到了段错误。

  5 void reverse2(char *s, int start, int end) {
  6   if (!s) return;
  7   char tmp;
  8   
  9   while (start < end) {
 10     tmp = s[end];
 11     *(s + end) = *(s + start);
 12     *(s + start) = tmp;
 13     ++start;
 14     --end;
 15   } 
 16 } 

Driver program that calls the function: 调用该函数的驱动程序:

int main() {
  /* Flavor1 works */
  string a = "hello world2012!";
  reverse1(a, 0, a.length() - 1);

  /* Flavor2 does not - segmentation fault */ 
  char *b = "hello world2012!";
  reverse2(b, 0, strlen(b) - 1);
}

I use gcc v 4.6.1 to compile my program. 我使用gcc v 4.6.1编译程序。 When stepping through the code with gdb, the program crashes at runtime with segmentation fault. 使用gdb单步执行代码时,程序会在运行时因分段错误而崩溃。

The char string s is not a const. 字符字符串s不是const。 Can someone please suggest what's going on here? 有人可以建议这里发生了什么吗? How do I fix this issue. 我该如何解决此问题。 Thanks. 谢谢。

Update: The reverse2 function is called on a string literal. 更新:在字符串文字上调用了reverse2函数。 The problem is I was trying to modify the string literal. 问题是我试图修改字符串文字。 As Jim and H2CO3 pointed out, this is an undefined behavior. 正如Jim和H2CO3所指出的,这是未定义的行为。

Now what's the exact difference between a string object (a) initialized with a string literal and a string literal (b)? 现在,使用字符串文字初始化的字符串对象(a)和字符串文字(b)之间的确切区别是什么?

It depends on how you invoke your routine. 这取决于您如何调用例程。 If end is the length of the array, as is common in C, then s[end] is not a valid reference ... it's one character beyond s . 如果end是数组的长度(如C中常见的那样),则s[end]不是有效的引用……它是s之外的一个字符。

Also, !s is not equivalent to C++ s.empty ... it tests whether the pointer is NULL, rather than whether the string is empty -- for that, use !*s , !s[0] , s[0] == '\\0' , strlen(s) == 0 , etc. 同样, !s不等于C ++ s.empty ...它测试指针是否为NULL,而不是字符串是否为空-为此,请使用!*s!s[0]s[0] == '\\0'strlen(s) == 0

The char string s is not a const. 字符字符串s不是const。

It could fail anyway if it's a string literal constant; 如果它是字符串文字常量,则无论如何都会失败。 writing to such a string is Undefined Behavior. 写入这样的字符串是未定义行为。

you can rewrite the code as below 您可以如下重写代码

void reverse(char *s, int start, int end) {
  if (!s) return;
  char tmp;

  if( end >= strlen(s) )
      end = strlen(s)-1;

  while (start < end) {
    tmp = s[end];
    *(s + end) = *(s + start);
    *(s + start) = tmp;
    ++start;
    --end;
  } 
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM