This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: Wherer is the Segmentation fault?
- From: Aubin LaBrosse <zoticus at gmail dot com>
- To: Vaibhav Kaushal <vaibhavkaushal123 at gmail dot com>
- Cc: "gcc-help at gcc dot gnu dot org" <gcc-help at gcc dot gnu dot org>
- Date: Tue, 30 Nov 2010 22:31:28 -0800
- Subject: Re: Wherer is the Segmentation fault?
- References: <1291184581.2628.3.camel@localhost>
In randomidxval - you never malloc entry.
Sent from my iPhone
On Nov 30, 2010, at 10:23 PM, Vaibhav Kaushal <vaibhavkaushal123@gmail.com> wrote:
> I am trying to dump a list of simple structure of two fields (roll
> number and name of student) into a file but it is failing. here is the
> code:
>
> ====================================
>
> #include <stdio.h>
>
> //structure of entry
> typedef struct {
> int rollno;
> char name[60];
> } entry;
>
> entry *newentry;
>
> entry* randomidxval(int x){
> printf("\n Entering randomidxval");
> entry *newentry;
> newentry->rollno = x;
> int i=0;
> for (i=0; i<60; i++) {
> newentry->name[i]=x;
> }
> printf("\n Exiting randomidxval");
> return newentry;
>
> }
>
> void create () {
> printf("\n Entering create");
>
> FILE *indx;
> //entry *temp;
> int i;
> indx = fopen("indx.dat", "wb" );
> if(indx) {
> for (i=0; i<2; i++) {
> printf("\n Entering loop");
> printf("\n Before allocation");
> //temp = randomidxval(i);
> printf("\n After allocation");
> printf("\n Before condition");
> if(0 != fwrite (randomidxval(i), sizeof(entry), 1 , indx)) {
> printf("\n Write Successful %d", i);
> } else {
> printf("\n Write Failed");
> }
> printf("\n After Condition");
> }
> } else {
> printf("\n File open failed");
> }
> //temp=malloc(1);
> //free(temp);
>
> /* Removing or altering the above two lines to free memory does not
> affect the error */
>
> printf("\n Close %s", fclose(indx) == 0 ? "succeeded" : "failed");
>
>
> /* It is in the following line that the problem exists. The fuction
> never executes the last line and shows a segmentation fault. No matter
> what I do, the function will fail before returning. I have tried a lot
> but no help */
>
> printf("\n Exiting create");
> return;
> }
>
> void search () {
> printf("\n Entering search");
> printf("\n Exiting search");
> return;
>
> }
>
> int main() {
> printf("\n Entering main");
>
> printf ("\n Actions: \n 1. Create index \n 2. Search \n Please choose
> your operation : ");
> int choice = 1;
> scanf ("%d", &choice);
> if(choice==1) {
> printf("\n Launching Create");
> create();
> printf("\n Create returned");
> } else {
> search();
> }
> printf (" \n ");
> //printf("\n %d \n", *choice);
> //free *choice;
> printf("\n Exiting main");
> return 0;
> }
>
> ======================================
>
>
> The problem is that the function create never returns!!
>
> can someone tell me the reason and how to resolve it? the program
> compiles well with no warnings or errors.
>
> My system is Fedora Linux 13 , 64-bit.
>