473,394 Members | 1,935 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Why segmentation fault

i am unable to find why following code is giving segmentation
fault.... way to produce seg fault: run the program... give input
12345678....enter any key except 'x'.... again give 12345678 as
input...then segmentation fault happens...

please somebody enlighten me...

#include <stdio.h>
#include<stdlib.h>

typedef struct
{
char project_id[40];
int project_ID;
} project_detail;
int
get_valid_int (char input[])
{
int count = 0;

while (input[count] != '\0' && count < 9)
{
if (input[count] >= '0' && input[count] <= '9')
count++;

else
return -1;
}
if (count != 8)
return -1;

else
return (atoi (input));
}
int
validate_projectid (int project_id)
{
FILE *fptr;
project_detail *temp;
int found = 0;

fptr = fopen ("PROJECT_DETAILS.DB", "r");
if (fptr != NULL)
{
fread (temp, sizeof (project_detail), 1, fptr);
while ((found == 0) && (!feof (fptr)))
{
if (temp->project_ID == project_id)
found = -1;
fread (temp, sizeof (project_detail), 1, fptr);
}
fclose (fptr);
}
return ((found >= 0) ? 1 : -1);
}
void
generation_of_project_details_add ()
{
project_detail proj_details;
char choice;
int search = 0;
FILE *f_ptr;

/*taking all the value from the keyboard */
do

{

/* Checking validity of Project detail ID */
do

{
printf ("\n Give the identification number of project\n");
scanf ("%s", proj_details.project_id);
fflush (stdin);
proj_details.project_ID = get_valid_int
(proj_details.project_id);
if (proj_details.project_ID == -1)

{
printf ("Invalid number. Pls enter again.\n");
continue;
}
search = validate_projectid (proj_details.project_ID);

/* Give error message if input is invalid */
if (proj_details.project_ID == -1 || search == -1)
printf
("\n The given input is invalid... Please try again...
\n");
}
while (proj_details.project_ID == -1 || search == -1); /* end
while

loop(inner) */
f_ptr = fopen ("PROJECT_DETAILS.DB", "a");
fwrite (&proj_details, sizeof (proj_details), 1, f_ptr);
fclose (f_ptr);
printf
("Do you want to input any other project detail. Press any key
to continue and press x to exit");
scanf (" %c", &choice);
}
while (choice != 'x');
}
int
main ()
{
generation_of_project_details_add ();
return 0;
}
Nov 13 '05 #1
3 8003

"Anks" <an******@mailcity.com> wrote in message
i am unable to find why following code is giving segmentation
fault.... way to produce seg fault: run the program... give input
12345678....enter any key except 'x'.... again give 12345678 as
input...then segmentation fault happens...

please somebody enlighten me...
You will find that segmentation faults are very common in newly-written C
programs. This is because C makes it so easy to accidentally write to memory
that you don't own.
Generally, you need to run a debugger to find out on which line the error
occurred. Usually it is then pretty obvious what is wrong.
If you have no debugger, or the debugger doesn't help, you need to put in
diagnostic printf()s (printf("Here\n") etc) and comment out sections of
code, to home in on the error.
#include <stdio.h>
#include<stdlib.h>

typedef struct
{
char project_id[40];
int project_ID;
} project_detail;
int
get_valid_int (char input[])
{
int count = 0;

while (input[count] != '\0' && count < 9)
{
if (input[count] >= '0' && input[count] <= '9')
count++;

else
return -1;
}
if (count != 8)
return -1;

else
return (atoi (input));
}
This function looks ok, provided input is a pointer to a valid address.
int
validate_projectid (int project_id)
{
FILE *fptr;
project_detail *temp;
int found = 0;

fptr = fopen ("PROJECT_DETAILS.DB", "r");
if (fptr != NULL)
{
fread (temp, sizeof (project_detail), 1, fptr);
This will cause an error. temp is an unitialised pointer pointing to who
knows where in memory, and you are writing data to it.
while ((found == 0) && (!feof (fptr)))
This use of feof() probably isn't correct. feof() returns true if the last
attempt to read failed.
{
if (temp->project_ID == project_id)
found = -1;
fread (temp, sizeof (project_detail), 1, fptr);
ditto here
}
fclose (fptr);
}
return ((found >= 0) ? 1 : -1);
}
void
generation_of_project_details_add ()
{
project_detail proj_details;
char choice;
int search = 0;
FILE *f_ptr;

/*taking all the value from the keyboard */
do

{

/* Checking validity of Project detail ID */
do

{
printf ("\n Give the identification number of project\n");
scanf ("%s", proj_details.project_id);
This could also cause a segfault, if someone enters more characters than the
array can hold.
fflush (stdin);
Flushing is for output streams only.
proj_details.project_ID = get_valid_int
(proj_details.project_id);
if (proj_details.project_ID == -1)

{
printf ("Invalid number. Pls enter again.\n");
continue;
}
search = validate_projectid (proj_details.project_ID);

/* Give error message if input is invalid */
if (proj_details.project_ID == -1 || search == -1)
printf
("\n The given input is invalid... Please try again...
\n");
}
while (proj_details.project_ID == -1 || search == -1); /* end
while

loop(inner) */
f_ptr = fopen ("PROJECT_DETAILS.DB", "a");
fwrite (&proj_details, sizeof (proj_details), 1, f_ptr);
fclose (f_ptr);
printf
("Do you want to input any other project detail. Press any key
to continue and press x to exit");
scanf (" %c", &choice);
}
while (choice != 'x');
}
int
main ()
{
generation_of_project_details_add ();
return 0;
}

Nov 13 '05 #2
an******@mailcity.com (Anks) wrote:
i am unable to find why following code is giving segmentation
fault.... way to produce seg fault: run the program... give input
12345678....enter any key except 'x'.... again give 12345678 as
input...then segmentation fault happens...

please somebody enlighten me... <SNIP>int
validate_projectid (int project_id)
{
FILE *fptr;
project_detail *temp;
int found = 0;

fptr = fopen ("PROJECT_DETAILS.DB", "r");
if (fptr != NULL)
{
fread (temp, sizeof (project_detail), 1, fptr);

Dang! Dang! Dang!
You failed to allocate some memory for temp to point to;
fread()ing to a non-existent buffer causes nasal demons, AKA
undefined behaviour.

IMHO you should write:

project_detail temp;
/* ^^^^^ */
[...]
fread ( &temp, sizeof temp, 1, fptr);
/* ^^^^^ */
[...]
if (temp.project_ID == project_id)
/* ^^^^^ */
[etc.]

<SNIP>

Two more hints:
- your sample program is way oversized; if you post code here
please make sure you cut it down to what is absolutely necessary
to exhibit the problem. Eventually this might result in finding
out what the problem /is/ by yourself... :)

- the overall program logic looks unnecessarily complex to me

Regards

Irrwahn
--
do not write: void main(...)
do not use gets()
do not cast the return value of malloc()
do not fflush( stdin )
read the c.l.c-faq: http://www.eskimo.com/~scs/C-faq/top.html
Nov 13 '05 #3
On Sat, 13 Sep 2003 17:22:20 UTC, an******@mailcity.com (Anks) wrote:
i am unable to find why following code is giving segmentation
fault.... way to produce seg fault: run the program... give input
12345678....enter any key except 'x'.... again give 12345678 as
input...then segmentation fault happens...
int
validate_projectid (int project_id)
{
FILE *fptr;
project_detail *temp;
int found = 0;

fptr = fopen ("PROJECT_DETAILS.DB", "r");
if (fptr != NULL)
{
fread (temp, sizeof (project_detail), 1, fptr); temp is uninitialised! while ((found == 0) && (!feof (fptr)))
{
if (temp->project_ID == project_id)
found = -1;
fread (temp, sizeof (project_detail), 1, fptr);
}
fclose (fptr);
}
return ((found >= 0) ? 1 : -1);
}
void
generation_of_project_details_add ()
{
project_detail proj_details;
char choice;
int search = 0;
FILE *f_ptr;

/*taking all the value from the keyboard */
do

{

/* Checking validity of Project detail ID */
do

{
printf ("\n Give the identification number of project\n");
scanf ("%s", proj_details.project_id);
fflush (stdin);


Undefined behavior as fflush() is only defind to work on output
streams.
--
Tschau/Bye
Herbert

eComStation 1.1 Deutsch Beta ist verügbar
Nov 13 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: sivignon | last post by:
Hi, I'm writing a php script which deals with 3 ORACLE databases. This script is launch by a script shell on an linux machine like this : /../php/bin/php ./MySript.php (PHP 4.3.3) My script...
3
by: diyanat | last post by:
i am writing a cgi script in C using the CGIC library, the script fails to run, i am using apache on linux error report from apache : internal server error Premature end of script headers:...
16
by: laberth | last post by:
I've got a segmentation fault on a calloc and I don'tunderstand why? Here is what I use : typedef struct noeud { int val; struct noeud *fgauche; struct noeud *fdroit; } *arbre; //for those...
3
by: Zheng Da | last post by:
Program received signal SIGSEGV, Segmentation fault. 0x40093343 in _int_malloc () from /lib/tls/libc.so.6 (gdb) bt #0 0x40093343 in _int_malloc () from /lib/tls/libc.so.6 #1 0x40094c54 in malloc...
5
by: Fra-it | last post by:
Hi everybody, I'm trying to make the following code running properly, but I can't get rid of the "SEGMENTATION FAULT" error message when executing. Reading some messages posted earlier, I...
18
by: Digital Puer | last post by:
Hi, I'm coming over from Java to C++, so please bear with me. In C++, is there a way for me to use exceptions to catch segmentation faults (e.g. when I access a location off the end of an array)?...
27
by: Paminu | last post by:
I have a wierd problem. In my main function I print "test" as the first thing. But if I run the call to node_alloc AFTER the printf call I get a segmentation fault and test is not printed! ...
7
by: pycraze | last post by:
I would like to ask a question. How do one handle the exception due to Segmentation fault due to Python ? Our bit operations and arithmetic manipulations are written in C and to some of our...
3
by: madunix | last post by:
My Server is suffering bad lag (High Utlization) I am running on that server Oracle10g with apache_1.3.35/ php-4.4.2 Web visitors retrieve data from the web by php calls through oci cobnnection...
6
by: DanielJohnson | last post by:
int main() { printf("\n Hello World"); main; return 0; } This program terminate just after one loop while the second program goes on infinitely untill segmentation fault (core dumped) on...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.