Thread overview
Segfault on simple struct manipulation
Aug 15, 2006
Peter Thomassen
Aug 15, 2006
Kirk McDonald
Aug 15, 2006
BCS
August 15, 2006
Hi there,

I'm coming from PHP and am very new to compiled languages, so maybe I'm completely wrong.

I have the following bitsort.d:

import std.stdio;
struct List {
        uint value;
}
void main() {
        List* list;
        writefln("This is shown.");
        list.value = 5;
        writefln("This is not shown.");
}

And this happens:

peter@tux ~/D $ dmd bitsort.d
gcc bitsort.o -o bitsort -m32 -lphobos -lpthread -lm
peter@tux ~/D $ ./bitsort
This is shown.
Segmentation fault (core dumped)
peter@tux ~/D $


Is this a bug?
Peter
August 15, 2006
Peter Thomassen wrote:
> Hi there,
> 
> I'm coming from PHP and am very new to compiled languages, so maybe I'm
> completely wrong.
> 
> I have the following bitsort.d:
> 
> import std.stdio;
> struct List {
>         uint value;
> }
> void main() {
>         List* list;
>         writefln("This is shown.");
>         list.value = 5;
>         writefln("This is not shown.");
> }
> 
> And this happens:
> 
> peter@tux ~/D $ dmd bitsort.d
> gcc bitsort.o -o bitsort -m32 -lphobos -lpthread -lm
> peter@tux ~/D $ ./bitsort
> This is shown.
> Segmentation fault (core dumped)
> peter@tux ~/D $ 
> 
> 
> Is this a bug?
> Peter

In your code. :-) Structs are a value type. Your main() should look like this:

void main() {
    List list;
    list.value = 5;
}

By saying "List* list;" you are declaring a pointer to a list, which is initialized to null. When you then say "list.value", you're dereferencing a null pointer, which causes the segfault.

-- 
Kirk McDonald
Pyd: Wrapping Python with D
http://pyd.dsource.org
August 15, 2006
Kirk McDonald wrote:
> Peter Thomassen wrote:
> 
>> Hi there,
>>
>> I'm coming from PHP and am very new to compiled languages, so maybe I'm
>> completely wrong.
>>
>> I have the following bitsort.d:
>>
>> import std.stdio;
>> struct List {
>>         uint value;
>> }
>> void main() {
>>         List* list;
>>         writefln("This is shown.");
>>         list.value = 5;
>>         writefln("This is not shown.");
>> }
>>
>> And this happens:
>>
>> peter@tux ~/D $ dmd bitsort.d
>> gcc bitsort.o -o bitsort -m32 -lphobos -lpthread -lm
>> peter@tux ~/D $ ./bitsort
>> This is shown.
>> Segmentation fault (core dumped)
>> peter@tux ~/D $
>>
>> Is this a bug?
>> Peter
> 
> 
> In your code. :-) Structs are a value type. Your main() should look like this:
> 
> void main() {
>     List list;
>     list.value = 5;
> }
> 
> By saying "List* list;" you are declaring a pointer to a list, which is initialized to null. When you then say "list.value", you're dereferencing a null pointer, which causes the segfault.
> 


If you want to use a pointer-to-List, assign something to it.

void main() {
    List back;
    List* list = new List;

    //or      List* list = &back;

    list.value = 5;
}