Jump to content

A segmentation fault...

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
veda87

veda87

    Programmer

  • Members
  • PipPipPipPip
  • 126 posts
I did a small program
#include <stdio.h>


typedef unsigned short u32;


int main()

{


        u32 *ptr = NULL;

        u32 *ptr1 = NULL;

        u32 temp;

        int i;


        ptr = malloc(512);

        if( ptr  == NULL) {

                printf("memory allocation failed\n");

                exit(1);

        }


        for(i=0 ; i< 512; i++){

                ptr[i] = 0;

        }


        for(i=0 ; i< 512; i++){

                printf("%d", ptr[i]);

        }


        temp = (u32)ptr;

        ptr1 = (u32 *)temp;


        for(i=0 ; i< 512; i++){

              printf("%d", ptr1[i]);

        }


        return 0;

}


when I compiled it with gcc, I got some warning
eg.c:29: warning: cast from pointer to integer of different size

eg.c:30: warning: cast to pointer from integer of different size


when I executed the code, it gave me segmentation fault...

can anyone tell me what is wrong with this code...

#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
Unsigned short is too small to hold a pointer. You need to use unsigned long (or unsigned int in 32 bit machines). I'd try to avoid manual input of pointers at all costs though, or even conversion to integers/longs. Unsigned short is 2 bytes in memory, whereas a pointer is 4 bytes in size on 32 bit machines.
Wow I changed my sig!

#3
Guest_h4x_*

Guest_h4x_*
  • Guests

Quote

can anyone tell me what is wrong with this code...
YES x86 SEGMENTS ARE INFERIOR

#4
TkTech

TkTech

    The Crazy One

  • Moderators
  • 1,396 posts
@h4x: ....even with the paging memory model, segments are still used. You just generally don't have to deal with them once you've setup your GDT.

@op: if your using GCC or a standards compliant compiler, check to see if your stdint.h has a uintptr_t defined. If so, that is the proffered type for storing a pointer. (However, note it is an optional type, although its almost always present)

#5
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,715 posts
Always use unsigned long for pointers. And don't listen to h4x, he has a history of spewing his opinion without knowing how the things he's criticizing even work.

H4x, really. It would be most enlightening if you would back up your "segmentation sucks" claims with concrete evidence, examples, etc. Just stating your opinion alone (in a very unprofessional manner, I might add) is not going to help anyone. To be honest, it's getting annoying.
sudo rm -rf /