C:将字符串反转到位.我在之前的一个问题中使用过prog.它编译好,但崩溃与segmenation故障

1 c pointers

我从main(C代码)调用Chris Conway提供的函数(如何在C或C++中反转字符串?).当我使用cygwin运行这个程序时,程序在while循环中崩溃(注释它破坏的行).你能解释一下这里出了什么问题.谢谢

#include <stdio.h>
#include <string.h>

void strrev(char* z);

int main()
{
        char *a;
    printf("before reverse: %s\n", a);
        strrev(a); // function provided by Chris Conway
    printf("after reverse: %s\n", a);
    return 0;
}

void strrev(char *str) {
  char temp, *end_ptr;

  /* If str is NULL or empty, do nothing */
  if( str == NULL || !(*str) )
    return;

  end_ptr = str + strlen(str) - 1;

  /* Swap the chars */
  while( end_ptr > str ) {
    temp = *str;
    *str = *end_ptr;  //crashes here (cygwin gives segmentation fault)
    *end_ptr = temp;  //for testing, if I comment out line above, it crashes here
    str++;
    end_ptr--;
  }
}
Run Code Online (Sandbox Code Playgroud)

vla*_*adr 8

该函数很好,但您main()似乎没有初始化字符串a.

尝试:

int main() {
  char a[1024];
  strcpy(a, "Some string");
  printf("before reverse: %s\n", a);
  strrev(a); // function provided by Chris Conway
  printf("after reverse: %s\n", a);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

请注意,我在内部创建了"Some string"的副本a(而不是直接分配char* a = "Some String"),因为尝试直接更改常量字符串将无法编译.如果你确实设法编译(例如,lax编译器,或者你通过cast/const_cast强制使用const),那么你的程序崩溃风险很高,因为"Some string"实际上是在读取的内存的一部分中 - 仅在某些系统上,这就是为什么必须在局部变量(即堆栈中)或新变量(使用new或malloc分配,即在堆上)进行复制的原因.