LinuxQuestions.org
Download your favorite Linux distribution at LQ ISO.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices

Reply
 
Search this Thread
Old 10-17-2005, 09:44 AM   #1
asahlot
Member
 
Registered: Sep 2005
Location: india
Distribution: Fedora Core 2
Posts: 62

Rep: Reputation: 15
why segmentation fault in this program?


Hello all,
I dont know why this tiny code is giving segmentation fault..
#include <stdio.h>

1. int main ()
2. {
3. int *a;
4. *a = 2;
5. printf ("%d\n", *a);
6. return 0;
7.}

when I tried gdb then segmentation fault was occurring in line no 4..
Please some body tell me what this error is and why it is coming in my program..
Thanx in advance
Regards
 
Old 10-17-2005, 10:01 AM   #2
jtshaw
Senior Member
 
Registered: Nov 2000
Location: Seattle, WA USA
Distribution: Ubuntu @ Home, RHEL @ Work
Posts: 3,892
Blog Entries: 1

Rep: Reputation: 66
Because your dereferencing a pointer which was never initialized to a known good value.

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

int main ()
{
    int *a = malloc (sizeof(int));
    *a = 2;
    printf ("%d\n", *a);
    return 0;
}
That will work better.....
 
Old 10-17-2005, 10:15 AM   #3
Winno
Member
 
Registered: Sep 2003
Location: Australia
Distribution: Fedora Core 3 / Mandrake 10.1 / Gentoo 2005.0
Posts: 100

Rep: Reputation: 15
The quick answer:
Replace *a with a. *a is a pointer and a is a variable. A variable gets memory automatically allocated to it while a pointer isn't.


The reason for the error is simple. Pointer a points to a block of memory, in this case, an integer (32 bits on x86). When you declared a, you did not allocate any memory to it, ie, it's not pointing to anything. By trying to change the block of memory it's pointing to (*a = 2, the program segfaults. To allocate memory, you need to call malloc or calloc, and call free when you have finished using it. This is called dynamic memory. In this simple case, you should not need to use it.

Last edited by Winno; 10-17-2005 at 10:21 AM.
 
Old 10-17-2005, 10:49 AM   #4
asahlot
Member
 
Registered: Sep 2005
Location: india
Distribution: Fedora Core 2
Posts: 62

Original Poster
Rep: Reputation: 15
Thanx jtshow..
I got the point now.. But yesterday I was trying another code that was also generating segmentation fault while I allocated memory using malloc ()..
The code is as under ..

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

typedef struct simple
{
int a;
char *c;
} example;

void print (example *);

int main ()
{
int i;
example *exp;
exp = (example *)malloc (sizeof (example) * 3); //allocated memory for 3 struct
for (i = 0; i <= 2; i++)
{
exp[i].a = i;
*(exp[i].c) = 'a' + i;
}
print (exp);
return 0;
} //end main


void print (example *p)
{
int i;
for (i = 0; i <= 2; i++)
printf ("a = %d, c = %c", p[i].a, *(p[i].c));
}


This code is also giving segmentation fault and I think its giving segmentation fault in line
*(exp[i].c) = 'a' + i;
I dont know why its giving while I used malloc to allocate memory..
Please help me out..
Thanx in advance
Regards
 
Old 10-17-2005, 10:54 AM   #5
deiussum
Member
 
Registered: Aug 2003
Location: Santa Clara, CA
Distribution: Slackware
Posts: 895

Rep: Reputation: 31
In that example you malloc memory for your example structs, but you do not allocate memory for the c member of your example structs...

BTW, if you put code tags around your code, it will be much more readable. (e.g. [ code]your code here[ /code], w/o the spaces in the bracket)
 
Old 10-17-2005, 11:03 AM   #6
asahlot
Member
 
Registered: Sep 2005
Location: india
Distribution: Fedora Core 2
Posts: 62

Original Poster
Rep: Reputation: 15
but how will I allocate memory for char *c.?
Please clear that too...
Thanx in advance.
Regards
 
Old 10-17-2005, 11:04 AM   #7
Quigi
Member
 
Registered: Mar 2003
Location: Cambridge, MA, USA
Distribution: Ubuntu (Dapper and Heron)
Posts: 377

Rep: Reputation: 31
By the way, it's not true that you MUST use dynamic memory (malloc, free & co) to make a pointer point to something meaningful. E.g.
Code:
int b;
int *a = &b;          /* now a points to b */
*a = 2;               /* same as   b = 2 */
In the second line, we assign the address of b to a. From that point on, "*a" is an alias for "b" (until a is changed again). Just thought this (fairly simple) aspect of pointers might help clarify the concept.

Last edited by Quigi; 10-17-2005 at 11:05 AM.
 
Old 10-17-2005, 11:10 AM   #8
deiussum
Member
 
Registered: Aug 2003
Location: Santa Clara, CA
Distribution: Slackware
Posts: 895

Rep: Reputation: 31
Quote:
Originally posted by asahlot
but how will I allocate memory for char *c.?
Please clear that too...
Thanx in advance.
Regards
It looks like you want to use the c in your example struct to hold a single char... in that case, you just need to use a char instead of a char*. If you really wanted to store a string in that, you would do something like:

Code:
exp[i].c = malloc(MAX_STRING_SIZE);
strcpy(exp[i].c, "string to copy");
Since you appear to just be assiging 'c' +i, you can just get away with changing your example struct to so:

Code:
typedef struct simple
{
    int a;
    char c;
} example;

Last edited by deiussum; 10-17-2005 at 11:11 AM.
 
Old 10-17-2005, 11:17 AM   #9
asahlot
Member
 
Registered: Sep 2005
Location: india
Distribution: Fedora Core 2
Posts: 62

Original Poster
Rep: Reputation: 15
Hello deiussum,
Actually I want to store string in that char *c..
But thing is that, when I am allocating memory for struct then why its not getting allocated for char *c too afterall its inside struct simple..???
Second thing if it really needs to allocate memory for char *c then how I will use malloc to allocate memory ? I mean, will I first allocate memory for struct simple and then second time again using malloc I will allocate memory for char *c..???
Hope its clear now..
So plz help out..
Thanx in advance.
Regards
 
Old 10-17-2005, 11:26 AM   #10
jtshaw
Senior Member
 
Registered: Nov 2000
Location: Seattle, WA USA
Distribution: Ubuntu @ Home, RHEL @ Work
Posts: 3,892
Blog Entries: 1

Rep: Reputation: 66
(exp[i].c) = malloc (sizeof(char) * length_of_string);
 
Old 10-17-2005, 11:37 AM   #11
itsme86
Senior Member
 
Registered: Jan 2004
Location: Oregon, USA
Distribution: Slackware
Posts: 1,246

Rep: Reputation: 58
Try picturing things laid out in memory. Every variable gets space in memory when it's declared, even pointers. The problem is, a pointer only gets memory reserved for the pointer itself. But a pointer is only (usually) 4-bytes big. Just enough to hold a memory address.

So when you do example *exp; you're only reserving memory for 4 bytes, but your struct is obviously bigger than that. So you do your malloc() to reserve space for 3 struct instances and assign that memory location to your exp pointer.

Now think about that malloc() call. You're asking it to reserve sizeof(example) bytes times 3. Remember that pointers are only 4-bytes big. So when you malloc() that memory for 3 struct instances, you're only reserving space for the c pointer itself. Not any memory that c might point to for actually storing data.

So after you malloc() memory for the struct, you'll need to malloc() memory for c to point to that can hold however many chars you want it to hold.
 
Old 10-17-2005, 12:00 PM   #12
asahlot
Member
 
Registered: Sep 2005
Location: india
Distribution: Fedora Core 2
Posts: 62

Original Poster
Rep: Reputation: 15
Hi all
Thanx to every body to help me out in understanding memory allocations..
Now things are al most quite clear to me.. Just one more question moving around in brain is, what is segmentation fault actually???
Is it generated when a process accesses memory not in its data space or wat else..? Please clear out it too..
Thanx in advance
Regards
 
Old 10-17-2005, 12:03 PM   #13
jtshaw
Senior Member
 
Registered: Nov 2000
Location: Seattle, WA USA
Distribution: Ubuntu @ Home, RHEL @ Work
Posts: 3,892
Blog Entries: 1

Rep: Reputation: 66
Because they did a better job then I would:

"In short, a segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way it is not allowed to (e.g., attempts to write a read-only location)."

Wikipedia - Segmentation Fault.
 
Old 10-17-2005, 12:47 PM   #14
itsme86
Senior Member
 
Registered: Jan 2004
Location: Oregon, USA
Distribution: Slackware
Posts: 1,246

Rep: Reputation: 58
Here's a little program that shows that a pointer to anything is always the same size (the second number on each line):
Code:
itsme@itsme:~/C$ cat ptrsize.c
#include <stdio.h>

struct blah
{
  int a;
  int b;
  int c;
  int d;
};

int main(void)
{
  printf("char : %d/%d\n", sizeof(char), sizeof(char *));
  printf("short: %d/%d\n", sizeof(short), sizeof(short *));
  printf("int  : %d/%d\n", sizeof(int), sizeof(int *));
  printf("float: %d/%d\n", sizeof(float), sizeof(float *));
  printf("blah : %d/%d\n", sizeof(struct blah), sizeof(struct blah *));

  return 0;
}
Code:
itsme@itsme:~/C$ ./ptrsize
char : 1/4
short: 2/4
int  : 4/4
float: 4/4
blah : 16/4
itsme@itsme:~/C$

Last edited by itsme86; 10-17-2005 at 12:52 PM.
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
yast segmentation fault, system freezing - nvidia driver at fault? BaltikaTroika Suse/Novell 2 12-02-2005 09:34 AM
Wine wont start program, segmentation fault, artsdsp nontoxic Linux - Software 3 03-21-2005 06:27 AM
Program received signal SIGSEGV, Segmentation fault ims_mca Linux - Distributions 0 03-09-2005 04:16 AM
libxml++: segmentation fault when exiting program. isl01jbe Programming 0 06-20-2004 05:47 AM
"segmentation fault" when run a simple c program acer_peri Programming 11 05-28-2004 04:14 AM


All times are GMT -5. The time now is 10:06 PM.

Main Menu
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration