LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   why segmentation fault in this program? (https://www.linuxquestions.org/questions/programming-9/why-segmentation-fault-in-this-program-373931/)

asahlot 10-17-2005 09:44 AM

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

jtshaw 10-17-2005 10:01 AM

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.....

Winno 10-17-2005 10:15 AM

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.

asahlot 10-17-2005 10:49 AM

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

deiussum 10-17-2005 10:54 AM

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)

asahlot 10-17-2005 11:03 AM

but how will I allocate memory for char *c.?
Please clear that too...
Thanx in advance.
Regards

Quigi 10-17-2005 11:04 AM

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.

deiussum 10-17-2005 11:10 AM

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;


asahlot 10-17-2005 11:17 AM

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

jtshaw 10-17-2005 11:26 AM

(exp[i].c) = malloc (sizeof(char) * length_of_string);

itsme86 10-17-2005 11:37 AM

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.

asahlot 10-17-2005 12:00 PM

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

jtshaw 10-17-2005 12:03 PM

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.

itsme86 10-17-2005 12:47 PM

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$



All times are GMT -5. The time now is 12:29 AM.