【问题标题】:C - segmentation fault and strlenC - 分段错误和 strlen
【发布时间】:2015-12-02 02:19:11
【问题描述】:

几个小时以来,我一直试图找出这个分段错误。每次我使用 char* find 时都会出现段错误。

char* find = malloc(sizeof(char) * 20);

displayMatrix(rowcol, matrix);
// (Don't mind that ^^^)

printf("Enter a word to find in the puzzle : \n");
scanf("%s", &find);
tolower(find);
len = strlen(find) + 1;

当我运行程序时,它会立即出现错误

len = strlen(find) + 1

有人知道它为什么这样做吗?提前致谢。

【问题讨论】:

  • 因为您可能打算使用scanf("%s", find);
  • tolower() 不能这样工作。要么禁用编译器警告,要么忽略它们。 sizeof(char) != 1 是不可能的,所以不要使用它。
  • 天哪。我一直没有使用 -Wall 。感谢您指出这一点。
  • printf("Here!\n");scanftolowerlen 之间进行调试打印,然后查看代码实际失败的位置。

标签: c pointers segmentation-fault


【解决方案1】:

scanf("%s", &find); 应该是scanf("%s", find); find 已经是字符串的地址了。

tolower 也不正确:int tolower ( int c ); 不是 int tolower ( char *c );

【讨论】:

  • 你没有收到tolower()
  • 我认为char* find = (char*) malloc(sizeof(char)*20);是分配内存的正确方式。
  • @nullpointer:这个高度赞成的问题和高度赞成的答案说不要强制转换 malloc 的结果(在 C 中,C++ 是一种不同的语言):stackoverflow.com/questions/605845/…
  • @dave:谢谢。
【解决方案2】:

其他方法是使用const char * 指向字符串文字并将其余代码更改为:

const char* find = (char*) malloc(sizeof(char)*20);
printf("Enter a word to find in the puzzle : \n");
scanf("%s", find);
printf("find says : I have got this saved under me %s \n", find); //just tried checking if it works
tolower(find); //this surely needs some correction,determine what you want
int len = strlen(find); //you won't require +1 using strlen
printf("%d : It Works Fine.",len);

【讨论】:

  • 你在哪里发现需要转换 malloc 的结果?
  • @ringø 指的是void *malloc(size_t); 我不应该这样做吗?
  • 好吧,谷歌一下。例如this
  • @ringø :thanx for that,这导致了为什么char* find = malloc(sizeof(char)*20); CLion 会显示Incompatible pointer types 'char*' and 'void*' ...不应该遵循这样的做法吗?
猜你喜欢
  • 1970-01-01
  • 2016-03-25
  • 1970-01-01
  • 2013-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多