473,803 Members | 3,534 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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....ent er 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_projec tid (int project_id)
{
FILE *fptr;
project_detail *temp;
int found = 0;

fptr = fopen ("PROJECT_DETAI LS.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_p roject_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.pr oject_id);
fflush (stdin);
proj_details.pr oject_ID = get_valid_int
(proj_details.p roject_id);
if (proj_details.p roject_ID == -1)

{
printf ("Invalid number. Pls enter again.\n");
continue;
}
search = validate_projec tid (proj_details.p roject_ID);

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

loop(inner) */
f_ptr = fopen ("PROJECT_DETAI LS.DB", "a");
fwrite (&proj_detail s, 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_p roject_details_ add ();
return 0;
}
Nov 13 '05 #1
3 8044

"Anks" <an******@mailc ity.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....ent er 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_projec tid (int project_id)
{
FILE *fptr;
project_detail *temp;
int found = 0;

fptr = fopen ("PROJECT_DETAI LS.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_p roject_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.pr oject_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.pr oject_ID = get_valid_int
(proj_details.p roject_id);
if (proj_details.p roject_ID == -1)

{
printf ("Invalid number. Pls enter again.\n");
continue;
}
search = validate_projec tid (proj_details.p roject_ID);

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

loop(inner) */
f_ptr = fopen ("PROJECT_DETAI LS.DB", "a");
fwrite (&proj_detail s, 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_p roject_details_ add ();
return 0;
}

Nov 13 '05 #2
an******@mailci ty.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....en ter any key except 'x'.... again give 12345678 as
input...then segmentation fault happens...

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

fptr = fopen ("PROJECT_DETAI LS.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_I D == 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******@mailci ty.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....ent er any key except 'x'.... again give 12345678 as
input...then segmentation fault happens...
int
validate_projec tid (int project_id)
{
FILE *fptr;
project_detail *temp;
int found = 0;

fptr = fopen ("PROJECT_DETAI LS.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_p roject_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.pr oject_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
6815
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 works fine and do all what I need. But at the end of the execution, I can read "Segmentation Fault". The segmentation fault appear at the end of my script execution,
3
1939
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: /var/www/cgi-bin/script.cgi when i debug the program i get Segmentation fault gdb ./script.cgi
16
9002
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 who don't speak french arbre means tree.
3
11451
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 () from /lib/tls/libc.so.6 It's really strange; I just call malloc() like "tmp=malloc(size);" the system gives me Segmentation fault I want to write a code to do like a dynamic array, and the code is as
5
2998
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 understood that a segmentation fault can occur whenever I declare a pointer and I leave it un-initialized. So I thought the problem here is with the (const char *)s in the stuct flightData (please note that I get the same fault declaring as char * the...
18
26124
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)? Thanks.
27
3375
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! #include <stdlib.h> #include <stdio.h> typedef struct _node_t {
7
5883
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 testcases we experiance Segmentation fault from the python libraries. If i know how to handle the exception for Segmentation fault , it will help me complete the run on any testcase , even if i experiance Seg Fault due to any one or many functions in...
3
5188
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 from 10g release2 PHP is configured with the following parameters './configure' '--prefix=/opt/oracle/php' '--with-apxs=/opt/oracle/apache/bin/apxs' '--with-config-file-path=/opt/oracle/apache/conf' '--enable-safe-mode' '--enable-session'...
6
5045
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 gcc. The only difference is that in first I only call "main" and in second call
0
9565
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10550
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10295
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9125
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7604
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6844
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5501
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5633
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2972
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.