【问题标题】:strcmp giving segmentation fault [duplicate]strcmp给出分段错误[重复]
【发布时间】:2014-04-26 22:54:43
【问题描述】:

这是我的代码给出分段错误

#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main(void) {
    char *get;
    scanf("%s", get);
    int k = strcmp("sachin", get);
    printf("%d", k);
}

感谢您的帮助;

【问题讨论】:

  • 这里的C++标签有误吗?如果没有,那么你的问题就更大了。
  • @BoBTFish 对不起 c++ 标签

标签: c pointers


【解决方案1】:
char *get;

上述语句将get 定义为指向字符的指针。它可以存储char 类型对象的地址,而不是字符本身。问题在于scanfstrcmp 调用。您需要定义一个字符数组来存储输入字符串。

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

int main(void) {
    // assuming max string length 40
    // +1 for the terminating null byte added by scanf

    char get[40+1];

    // "%40s" means write at most 40 characters
    // into the buffer get and then add the null byte
    // at the end. This is to guard against buffer overrun by
    // scanf in case the input string is too large for get to store

    scanf("%40s", get);
    int k = strcmp("sachin", get);
    printf("%d", k);

    return 0;
}

【讨论】:

    【解决方案2】:

    你需要为指针get分配内存。

    或者使用 char 数组:

    char   get[MAX_SIZE];
    scanf("%s",get);
    

    当你声明一个指针时,它并不指向任何内存地址。您必须通过malloc(c 风格)或new(c++ 风格)为该指针显式分配内存。

    您还需要分别通过free / delete 自己管理清理操作。

    【讨论】:

    • 我不明白为什么我必须分配我声明时已经分配的内存;
    • @SachinSetiya 如果你声明了一些内存只分配给声明的对象本身——在这种情况下是指针。
    • @SachinSetiya No. 虽然声明您只是指定指针可以指向一个字符。它不会立即开始指向。
    • 谢谢先生,我明白了,但是有没有办法获得没有最大长度的可变长度字符串
    【解决方案3】:

    你肯定遇到了段错误。 您告诉您的计算机将用户输入写入未初始化的指针。

    char   *get; // just a pointer that may wildly points anywhere
    scanf("%s",get);
    

    将 get 定义为一些字符数组

    char get[SOME_LARGE_CONSTANTS_THAT_CLEARLY_IS_LARGER_THAN_YOUR_USER_INPUT];
    

    【讨论】:

    • 我不想使用固定数组破坏空间,所以使用了 char *
    • @SachinSetiya 这是不可能的!您的指针不指向任何缓冲区!您必须为输入例程可能写入的内存分配足够的内存。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 2011-11-11
    • 1970-01-01
    • 1970-01-01
    • 2015-08-14
    • 1970-01-01
    相关资源
    最近更新 更多