提取字符串崩溃的代码

标签 c string pointers segmentation-fault

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

#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

然后它崩溃了。 我不明白问题是什么。

最佳答案

首先,你需要改变

scanf("%d", till);

scanf("%d", &till);

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

然后,还有很多问题,比如

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

也就是说,

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

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

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

关于提取字符串崩溃的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32891356/

相关文章:

C - 时间值到 uint64_t

c - 我应该如何查看GDB中特定地址的堆栈数据?

javascript - 在 Javascript 中更新 JSON 文件

c - strcpy 函数无法正常工作

c - 在 C 中使用 qsort() 和结构

c - 指向指针数组的指针返回初始地址

c - 如何输入两个字符串?

c - 使用 Allegro5 在 C 中播放声音文件

php - 如何使用 PHP 用 HTML 注释字符串(即如何通过偏移量维护有效的 HTML 将 HTML 标记插入字符串)?

c++ - 如何使用模板将结构存储在指针数组中