C语言 消毒剂的用途:未知地址0xfffffffffffffffff上的SEGV是指什么?

zpjtge22  于 2023-02-07  发布在  其他
关注(0)|答案(1)|浏览(166)

我在代码中得到一个错误,我不知道它是什么意思,这是我第一次遇到它。

AddressSanitizer:DEADLYSIGNAL
=================================================================
==30==ERROR: AddressSanitizer: SEGV on unknown address 0xffffffffffffffbe (pc 0x7f3dfc3c588c bp 0x7ffe82c73070 sp 0x7ffe82c727d0 T0)
==30==The signal is caused by a READ memory access.
    #0 0x7f3dfc3c588b  (/lib/x86_64-linux-gnu/libasan.so.5+0xd688b)
    #3 0x7f3dfb7b70b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV (/lib/x86_64-linux-gnu/libasan.so.5+0xd688b) 
==30==ABORTING

我需要把一行中的每个单词都反转过来。我认为这发生在第二个循环中。我的想法是找到每个单词的第一个和最后一个索引。这是我的代码:

char * reverseWords(char * s){
    int n = strlen(s);
char *res = malloc(sizeof(char) * n);
int firstI, lastI;
for (int i = 0; i < n; i++){
    firstI = i;
    while (++i < n && strcmp(res[i], ' ') == 0){
        lastI = i - 1;
    }
    while (firstI > lastI){
        char temp = res[firstI];
        res[firstI++] =  res[lastI];
        res[lastI--] = temp;
    }
}
return res;
}

新码

char * reverseWords(char * s){
    int n = strlen(s);
char *res = malloc(n + 1);
strcpy(res, s);
int firstI, lastI;
for (int i = 0; i < n; i++){
    firstI = i;
    while (++i < n && res[i] == ' '){
        lastI = i - 1;
    }
    while (firstI > lastI){
        char temp = res[firstI];
        res[firstI++] =  res[lastI];
        res[lastI--] = temp;
    }
}
return res;
}
djmepvbi

djmepvbi1#

因一个错误而关闭:

int n = strlen(s);
char *res = malloc(sizeof(char) * n);

strlen()不计算终止空字节。您没有为其分配空间。

缺少空终止符:

return res;

在返回之前,不能以null终止res

strcmp()比较字符串:

strcmp(res[i], ' ')

strcmp()的参数必须是char * s,而不是char s。
旁白:如果malloc()返回NULL,则代码将面临未定义行为的风险。
编辑:当前代码太复杂了。我简化了一些东西,并添加了一些检查。

static char *reverseWords(char *str)
  {
      /* NULL pointer. */
      if (!str) {
          return 0;
      }
      /* Empty string. */
      if (*str == '\0') {
          return 0;
      }
      /* Assuming it's null-terminated. */
      char *src = str;
      char *dest = src + (strlen(str) - 1); /* -1 for the null-byte. */
 
      /* ++ and -- have higher precedence than the * operator.
      *  But, in an expression, they return the old value of their
      *  operand. So this copies first, then increments the pointer
      *  point to the next char.
      */
      while (src < dest) {
          char tmp = *src;
          *src++ = *dest;
          *dest-- = tmp;
      }
      return str;
  }

示例I/O:

Input: Hello
 Output: olleH

相关问题