2017-05-26 134 views
0

我不知道什么是错我的代码:分段错误

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

char* splitstr(char* str, int part, char search) { 
    char* out; 
    int i; 
    int result = 0; 
    for(i=0; str[i]!='\0'; i++) { 
     if(str[i] == search) { 
      result = 1; 
      break; 
     } 
    } 
    if(result == 0) { 
     if(part == 1) { 
      return str; 
     } else { 
      return ""; 
     } 
    } 
    int j; 
    int k; 
    if(part == 2) { 
     for(j = 0; j < i; j++) { 
      out[j] = str[j]; 
     } 
     out[j] = '\0'; 
    } else { 
     for(k = 0,j = i+1; j <= strlen(str)-1; j++, k++) { 
      out[k] = str[j]; 
     } 
     out[k] = '\0'; 
    } 
    return out; 
} 
} 

int main() { 
    printf("Starting program:\n"); 
    char* str = "Hello World!"; 
    char* a = splitstr(str, 1, ' '); 
    char* b = splitstr(str, 1, ' '); 
    printf("A is %s\n", a); 
    printf("B is %s\n", b); 
} 

它返回的输出如下:

Starting program: 
Segmentation Fault: 11 

gdb调试后,我发现,错误是在线路30上发生(通过使用断点),在循环的第一次迭代中,当它试图设置out[0]out[k])到str[6]str[j])。为什么会触发分段错误?我只是将字符串中的一个字符更改为另一个字符!

+0

注意:发布的代码在声明之后有一个不寻常的大括号'}':'return out;' – user3629249

回答

6

有一个在out没有字符串。这是一个未初始化的指针,因为没有为写入分配内存,所以无法写入。这样做会触发未定义的行为,这就是您的程序崩溃的原因。

您必须分配一些,通常使用malloc()

另外,作为一个单纯的回顾钞类,第一循环相当于:

const int result = strchr(str, search) != NULL; 
0

的主要问题是这一行:

char* out; 

只是声明了一个指针,但不设置该指针指向任何特定内存(应用程序拥有的)

所以此行:

out[j] = str[j]; 

正在为内存中的某个随机位置分配值。

正确的VIA或者那样的问题:

char *out[ strlen(str) +1 ]; // uses variable length array feature 

或通过:

char *out = malloc(strlen(str) +1); 
if(!out) 
{ // malloc failed 
    perror("malloc failed"); 
    exit(EXIT_FAILURE); 
} 

// implied else, malloc successful 

你的编译器应该告诉你关于这个问题,像声明:

filename.c:43:16: warning: 'out' may be used uninitialized in this function [-Wmaybe-uninitialized] 

编译时,请始终启用警告,然后修复这些警告。

(为gcc,至少使用:-Wall -Wextra -pedantic我还使用:-Wconversion -std=gnu11

如果使用-Wconversion选项,那么这也将是由编译器输出:

filename.c:51:30: warning: comparison between signed and unsigned integer expression [-Wsign-compare]