当前位置: 动力学知识库 > 问答 > 编程问答 >

c - Getting Error Segmentation fault

问题描述:

My program works fine but has a strange bug... the last line on the input cannot be blank otherwise it throws the error Segmentation fault (core dumped)... Any idea why that would be happening?

Here is my code:

#include<stdlib.h>

#include <stdio.h>

#include <string.h>

#define NUM 25

#define LEN 1000

int stringCompare(char str1[],char str2[]);

void stringCopy(char str1[],char str2[]);

int main()

{

char tmp[25];

int i=0,j=0;

char Strings[NUM][LEN];

printf("enter %d strings, one at a time:\n", NUM);

for(i=0;i<NUM;++i)

{

printf("String %d : ",(i+1));

fgets(Strings[i],LEN-2,stdin);

}

puts("these are the strings you entered:");

for(i=0;i<NUM;++i)

{

printf("%s",Strings[i]);

}

for(i=1;i<NUM;i++)

{

for(j=0;j<NUM-1;j++)

{

if(stringCompare(Strings[j],Strings[j+1]) > 0)

{

stringCopy(tmp,Strings[j]);

stringCopy(Strings[j],Strings[j+1]);

stringCopy(Strings[j+1],tmp);

}

}

}

/* Output sorted list */

puts("These are the strings alphabetical order:");

for(i=0;i<NUM;i++)

{

printf("%s",Strings[i]);

}

return 0;

}

int stringCompare(char str1[],char str2[]){

int i=0,flag=0;

while(str1[i]!='\0' && str2[i]!='\0')

{

if(str1[i]!=str2[i]){

return str1[i] - str2[i];

}

i++;

}

return 0;

}

void stringCopy(char str1[],char str2[]){

int i=0;

while(str2[i]!='\0'){

str1[i] = str2[i];

i++;

}

str1[i]='\0';

}

网友答案:

One issue that I see in the above code is that you have an array of strings with a maximum length of 1000 and you use a temporary array to swap them, however the temporary array is of size 25, and you may potentially try to copy a string of length 1000 into it causing a buffer overrun.

tmp[25];

should be

tmp[LEN];

If at least one of the strings in your input is longer than 23 characters (subtracting 2 for '\0' and '\n', your program may exhibit undefined behavior when you copy one of these long strings into tmp.

分享给朋友:
您可能感兴趣的文章:
随机阅读: