我为什么会出现分段错误(核心转储) [英] Why am I getting segmantation fault (core dumped)
问题描述
#include < stdio.h >
int main()
{
char * S,I;
printf( 输入字符串:);
scanf( %s,s);
for (i = 0 ; s [i]!= ' \0'; ++ i);
printf( 字符串长度:%d \ n,i);
return 0 ;
}
输出:输入一个字符串:jeevan
字符串长度:6
分段错误(核心转储)
char * s;
没有为scanf读取分配任何内存 - 它只是声明一个指针 - 所以你需要使用(例如)
s = malloc( 100 );
为99个字符的字符串提供足够的空间(加上终止的nul)iirc
问题是,如何确保用户输入的字符不超过99个? - 答案是,使用像这样的scanf,你不能 - 它'危险'
我看过有关scanf的说明符的说法,暗示使用%ms获取scanf为你分配内存,但是,我无法证明这种用法[/ edit]
我似乎记住你也可以使用scanf作为长度说明符,但是,你仍然必须使用malloc或声明s作为char数组,当用户键入你允许的字符数时,它会变得混乱
- 你应该使用更安全的东西,比如fgets()而不是
'g'
你没有为这个字符串分配任何内存,快速和脏的修复将是:
#include< stdio.h>
int main()
{
char s [ 255 跨度>],I;
printf( 输入字符串:);
scanf( %s,s);
for (i = 0 ; s [i]!= ' \0'; ++ i);
printf( 字符串长度:%d \ n,i);
return 0 ;
}
一个不错的读物:字符串溢出with scanf [ ^ ]。
guys, whats wrong here?
#include <stdio.h>
int main()
{
char *s,i;
printf("Enter a string: ");
scanf("%s",s);
for(i=0; s[i]!='\0'; ++i);
printf("Length of string: %d \n",i);
return 0;
}
output:Enter a string: jeevan
Length of string: 6
Segmentation fault (core dumped)
char *s;
doesn't allocate any memory for the scanf read - it just declares a pointer - so you need to use (for example)
s = malloc(100);
to get enough space for a 99 character string (plus the terminating nul) iirc
the issue then is, how do you ensure your user doesn't type more than 99 characters ? - and the answer is, using scanf like this, you cant - its 'dangerous'
[edit] I have seen talk of a specifier for scanf, that alludes to using "%ms" gets scanf to allocate the memory for you, but, I cannot attest to this form of usage [/edit]
[edit] I seem to remember that you could also a length specifier with scanf, but, you'd still have to use the malloc or declare s as an array of char, and, it gets messy when the user types over the number of characters you've allowed for [edit]
- you should use something safer, like fgets() instead
'g'
You have not allocate any memory for this string, the quick and dirty fix would be:
#include <stdio.h> int main() { char s[255],i; printf("Enter a string: "); scanf("%s",s); for(i=0; s[i]!='\0'; ++i); printf("Length of string: %d \n",i); return 0; }
A nice reading: "String overflows with scanf"[^].
这篇关于我为什么会出现分段错误(核心转储)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!