Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
I'm having some trouble with my C code and I keep having the same error repeatedly.. Any help would be great..?
I keep having the same repeated error of "Segmentation Fault" at the end of running the program.
My code is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <math.h>
#include <string.h>
main ()
{
int i, n = 0;
char *x[10];
printf("Enter each string on a separate line below\n\n");
printf("Type \'END\' when finished\n\n");
do {
x[n] = (char *) malloc(12 * sizeof(char));
printf("string %d: ", n + 1);
scanf("%s", x[n]);
}
while (strcmp(x[n++], "END"));
/* reorder the list of strings */
reorder(--n, x);
/* display the reordered list of strings */
printf("\n\nReordered List of STrings:\n");
for (i = 0; i < n; ++i)
printf("\nstring %d: %s", i + 1,x[i]);
}
void reorder(int n, char *x[])
{
char *temp;
int i, item;
for (item = 0; item < n - 1; ++item)
for (i = item + 1; i < n; ++i)
if (strcmp(x[item], x[i]) > 0) {
temp = x[item];
x[item] = x[i];
x[i] = temp;
}
return;
}
3 Answers
- cjaLv 71 decade agoFavorite Answer
You have three dangerous things happening here. 1) you're only allocating 12 bytes for each character array pointed to by elements of x[ ], 2) you're are taking whatever is entered by the user and letting scanf store it at x[n], even if the entered string is > 12 characters, and 3) you've declared x[ ] to be of length 10, but you're not limiting the user to entering a max of 10 strings. Any of these put you at risk of referencing unallocated memory, leading to your seg fault.
- Anonymous1 decade ago
Since you've got return at the end of main, main needs to return a type, which means you should have declaired it like:
int main()
(but usually, if not specified defaults to int any way. Do you compile with the -Wall switch?)
Also, you need a function prototype declaration for the reorder() function so it shows this program has a function called reorder() and that it recieves an int and a char like:
void reorder(int, char**);
(Put this under your header declarations, before main)
****** EDIT ******
I got your program working and I Like It!!!
How long have you been programming in C? It's good.
P.S. cja - thanks for the thumbs down BUT I got it working.
I couldn't have been that far off the money if I got it working!!! Could I?
- BillLv 41 decade ago
If adding the return to main() doesn't help, I'm afraid you've got some work ahead of you.
SegFault is a very vague error, but basically it means you're pointing to a nonexistent memory at some point.