【问题标题】:Code for extracting string crashes提取字符串崩溃的代码
【发布时间】:2015-10-01 15:25:55
【问题描述】:

我编写了这段代码来接受一个字符串,直到它应该提取一个字符串并打印它。 代码如下:

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

int strlen(char s[]){
    int i = 0;
    while(s[i]!='\0')
        i++;
    return i;
}

char *extract(char s[], int n){
    char *result = (char *)malloc(sizeof(char)*3);
    for(int j=0;j<n;j++){
        result[j]=s[j];
    }
    return result;
}

int main(){
char str[100];
int till;
printf("Enter a string: ");
scanf("%s", str);

printf("Until where to extract: ");
scanf("%d", till);

char *ret = extract(str, till);

printf("%s is extracted", ret);

return 0;
}

会发生这样的事情:

Enter a string: hello
Enter from where to extract: 2

然后它崩溃了。 我不明白问题出在哪里。

【问题讨论】:

标签: c string pointers segmentation-fault


【解决方案1】:

首先,你需要改变

scanf("%d", till);

scanf("%d", &till);

as scanf() 需要一个 指向数据类型的指针 用于提供的格式说明符。使用错误类型的参数会导致undefined behavior

然后,有很多问题,比如

  1. 您只分配了 3 个chars,您根据n 的传入值在其中循环。
  2. 您从未检查过malloc() 是否成功。
  3. 您没有以空值终止您打算稍后用作字符串result

也就是说,

  1. 您应该始终限制字符串的输入以避免溢出的可能性,例如

    scanf("%99s", str);  //considering the length of the array is 100.
    
  2. string.h 提供了一个库函数 strlen()。即使您想推出自己的功能,也请尝试遵循不同的命名约定。

  3. 你没有free()分配的内存。

【讨论】:

    【解决方案2】:

    我在编译代码时将 -Wall 添加到命令中,您会看到

    test.c:40:2: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]
      scanf("%d", till);
      ^
    

    然后改就必须改成scanf("%d", &amp;till);

    【讨论】:

      【解决方案3】:

      除了其他建议:

      char *result = (char *)malloc(sizeof(char)*3);
      

      应该是:

      char *result = malloc(n + 1);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-07
        • 2019-09-01
        • 2017-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多