What line is at fault -- segfault, that is...?
I'm relatively new to C (and completely new to StackOverflow - hey guys!), and this segfault has been giving me no surcease of sorrow for the past few hours (DevC++ on a windows machine). It's just a simple palindrome prime program, but it's really giving me a hard time. I'm not generally a novice programmer like it seems here, but... Good god. Now I remember why I wanted to get away from C++ and to Python so quickly.
#include <开发者_JAVA百科;stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
FILE *outputFile;
char buffer[81];
char* strrev();
int bytesWritten;
char* strI = 0;
char *strrev(char str[])
{
char *p1 =NULL;
char *p2 =NULL;
if (! str || ! *str)
return str;
for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2)
{
*p1 ^= *p2;
*p2 ^= *p1;
*p1 ^= *p2;
}
return str;
}
main()
{
int isPrime(int);
int i,j;
outputFile = fopen("DD:OUTPUT", "w");
if (outputFile == NULL)
{
printf("open error: %d/%s\n", errno, strerror(errno));
exit(99);
}
for (i=1; i<15000; i++)
{
if (isPrime(i)==1)
{
bytesWritten = sprintf(buffer,"%d is primepal!\n",i);
fwrite(buffer, 1, bytesWritten, outputFile);
}
}
fclose(outputFile);
return 0;
}
int isPrime(int myInt)
{
int loop;
for (loop = 2; loop < myInt/2+1; loop++)
sprintf(strI, "%s%d", 10, myInt);
{
if (myInt%loop==0 && (atoi(strrev(strI))-myInt)==0)
{
return 0;
}
return 1;
}
}
I apologize ahead of time if this is a dumb question, and the answer is very obvious -- but I've officially hit the limit where no matter how logical an answer, I've been coding the same problem for too long for it to make any sense. And also, segfaults are horrible beasts. Thank you ahead of time for anything you have to offer!
~ Jordan
The line sprintf(strI, "%s%d", 10, myInt);
is likely crashing.
- You have not allocated any space for
strI
, it's defined aschar* strI = 0;
Make it achar[64]
, or a suitable size. - You're giving the wrong arguments to sprintf, "%s%d" says the first parameter should be a string ("%s") , but you give it an int. Change %s to %d
Some other issues:
- Don't use *p1 ^= *p2; hack to to swap variables, there's many cases where this does not work. Do it properly with a temp variable.
- main() calls isPrime(), but there's no prototype for isPrime at that time. Place
int isPrime(int myInt);
somewhere before main(). - The prototype for your strrev function should be
char *strrev(char str[]);
and notchar *strrev()
Segfaults don't have to be as bad as you're experiencing. Compile the program with debugging symbols (add -g to gcc) and run it in gdb. After the segfault, type bt in gdb and press enter. It will tell you the exact line of your segfault.
for (loop = 2; loop < myInt/2+1; loop++)
sprintf(strI, "%s%d", 10, myInt);
{
if (myInt%loop==0 && (atoi(strrev(strI))-myInt)==0)
You might want to double-check where you've got that brace in relation to the for
. This isn't python, and indentation alone doesn't cut it.
精彩评论