473,776 Members | 1,498 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Please help me spot the difference

I have a small piece of code that compiles but does not perform like I
want it to.

This code works:
----------------

void *y0;
void *y1;
void *y2;
void *y3;
void *y4;

y0 = ssGetOutputPort Signal(S,0);
y1 = ssGetOutputPort Signal(S,1);
y2 = ssGetOutputPort Signal(S,2);
y3 = ssGetOutputPort Signal(S,3);
y4 = ssGetOutputPort Signal(S,4);
This code doesn't work:
-----------------------

void **y;
int i = 0;

*y = malloc(5 * sizeof(void*));

while (i < 5)
{
*(y+i) = ssGetOutputPort Signal(S,i);
i++;
}
I've also tried to use *y[i] and *(y[i]) instead of *(y+i). They all
compile, but does also violate my segments :]

Can anyone tell me why i get segmentation violation?
To me i seems like the code should perform somewhat similar, but I
regulary mess up when using pointers and pointers-to-pointers.

I know I have to use free(*y) later on. I also know that I ought to
check if malloc returns NULL. But neither seems to generate my problem.

I beg of all of you C gurus out there, please help poor little stupid
me. I know that some of you hardcore C guys probably lived inside a
computercabinet since birth and dream dreams in scrolling green symbols,
which sometimes fork()'s into severel parallel dream-threads.
Andreas
Oct 23 '06 #1
9 1687

"Andreas Vinther" <an************ *@gmail.comwrot e in message
news:45******** *************@d reader1.cyberci ty.dk...
>I have a small piece of code that compiles but does not perform like I want
it to.

This code works:
----------------

void *y0;
void *y1;
void *y2;
void *y3;
void *y4;

y0 = ssGetOutputPort Signal(S,0);
y1 = ssGetOutputPort Signal(S,1);
y2 = ssGetOutputPort Signal(S,2);
y3 = ssGetOutputPort Signal(S,3);
y4 = ssGetOutputPort Signal(S,4);
This code doesn't work:
-----------------------

void **y;
int i = 0;

*y = malloc(5 * sizeof(void*));

while (i < 5)
{
*(y+i) = ssGetOutputPort Signal(S,i);
i++;
}
I've also tried to use *y[i] and *(y[i]) instead of *(y+i). They all
compile, but does also violate my segments :]

Can anyone tell me why i get segmentation violation?
To me i seems like the code should perform somewhat similar, but I
regulary mess up when using pointers and pointers-to-pointers.

I know I have to use free(*y) later on. I also know that I ought to check
if malloc returns NULL. But neither seems to generate my problem.

I beg of all of you C gurus out there, please help poor little stupid me.
I know that some of you hardcore C guys probably lived inside a
computercabinet since birth and dream dreams in scrolling green symbols,
which sometimes fork()'s into severel parallel dream-threads.
Andreas
Instead of
*y = malloc(5 * sizeof(void*));
try this
y = (void **)malloc(5 * sizeof(void*));

I think that the typecast is not really needed in C
(but is needed in C++) so I've added it anyway.

Serafeim
Oct 23 '06 #2
Ico
Andreas Vinther <an************ *@gmail.comwrot e:
I have a small piece of code that compiles but does not perform like I
want it to.

This code doesn't work:
-----------------------

void **y;
int i = 0;

*y = malloc(5 * sizeof(void*));
Think about what you are doing with the result of malloc() here, where
does it get stored to ?
I beg of all of you C gurus out there, please help poor little stupid
me. I know that some of you hardcore C guys probably lived inside a
computercabinet since birth and dream dreams in scrolling green symbols,
which sometimes fork()'s into severel parallel dream-threads.
No, you won't find these people here; both fork() and threads are not
part of ansi C. Try again comp.os.unix.pr ogrammer.

--
:wq
^X^Cy^K^X^C^C^C ^C
Oct 23 '06 #3
and with y = malloc(5 * sizeof(void*)); ?
(instead of *y = )
Andreas Vinther a écrit :
I have a small piece of code that compiles but does not perform like I
want it to.

This code works:
----------------

void *y0;
void *y1;
void *y2;
void *y3;
void *y4;

y0 = ssGetOutputPort Signal(S,0);
y1 = ssGetOutputPort Signal(S,1);
y2 = ssGetOutputPort Signal(S,2);
y3 = ssGetOutputPort Signal(S,3);
y4 = ssGetOutputPort Signal(S,4);
This code doesn't work:
-----------------------

void **y;
int i = 0;

*y = malloc(5 * sizeof(void*));

while (i < 5)
{
*(y+i) = ssGetOutputPort Signal(S,i);
i++;
}
I've also tried to use *y[i] and *(y[i]) instead of *(y+i). They all
compile, but does also violate my segments :]

Can anyone tell me why i get segmentation violation?
To me i seems like the code should perform somewhat similar, but I
regulary mess up when using pointers and pointers-to-pointers.

I know I have to use free(*y) later on. I also know that I ought to
check if malloc returns NULL. But neither seems to generate my problem.

I beg of all of you C gurus out there, please help poor little stupid
me. I know that some of you hardcore C guys probably lived inside a
computercabinet since birth and dream dreams in scrolling green symbols,
which sometimes fork()'s into severel parallel dream-threads.
Andreas
Oct 23 '06 #4
Andreas Vinther <an************ *@gmail.comwrot e:
I have a small piece of code that compiles but does not perform like I
want it to.
void **y;
int i = 0;
*y = malloc(5 * sizeof(void*));
You assign to something 'y' is pointing to, but since 'y' isn't
initialized things go badly wrong. Moreover, you try to assign to
a void pointer something that points to a set of 5 void pointers -
that might give you a hint that something isn't correct here. Make
that

y = malloc(5 * sizeof(void*));

or, even better,

y = malloc(5 * sizeof *y);

to be not dependent on what type 'y' actually has.
while (i < 5)
{
*(y+i) = ssGetOutputPort Signal(S,i);
The "*(y+i)" bit can also be written as "y[i]", both forms are
identical.
i++;
}
I've also tried to use *y[i] and *(y[i]) instead of *(y+i). They all
compile, but does also violate my segments :]
You probably will get some compiler warnings for these attempts if
you raise its warning level - if 'y' is a pointer-to-pointer to void,
then y[i] is of type pointer to void, and thus assigning to *y[i] or
*(y[i]) (which is the same, the [] binds more tightly than the de-
reference operator *) would mean you try to assign a value to a void,
which of course isn't allowed.
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\______________ ____________ http://toerring.de
Oct 23 '06 #5
"Papastefan os Serafeim" <se******@otene t.grwrote:
"Andreas Vinther" <an************ *@gmail.comwrot e in message
void **y;
int i = 0;

*y = malloc(5 * sizeof(void*));

while (i < 5)
{
*(y+i) = ssGetOutputPort Signal(S,i);
i++;
}
Instead of
*y = malloc(5 * sizeof(void*));
try this
y = (void **)malloc(5 * sizeof(void*));

I think that the typecast is not really needed in C
The cast is a Bad Thing in C, and shouldn't be there. For example, one
of the parts of the code Mr. Vinther did not show us is the bit where he
#includes his standard headers. If he forgot to #include <stdlib.h>,
that's a significant error which might have an impact on his problem,
and the compiler should warn him of this if its error level is set high
enough - but with your cast, it probably never will.

Richard
Oct 23 '06 #6
Jens Thoms Toerring skrev:
Andreas Vinther <an************ *@gmail.comwrot e:
>I have a small piece of code that compiles but does not perform like I
want it to.
> void **y;
int i = 0;
*y = malloc(5 * sizeof(void*));

You assign to something 'y' is pointing to, but since 'y' isn't
initialized things go badly wrong. Moreover, you try to assign to
a void pointer something that points to a set of 5 void pointers -
That is what I want it to do. I want a void pointer that points to 5
other void pointers.

Ofcourse...that 's it.. Stupid me I haven't initialised it yet. So if I add:
void *x
y = &x;
to my original code it should work.

I'm not at my own computer right now, but I think that's it.
I't not beautifull but it I think it'll work.

I'll try I as soon as I get home... Thanks a lot y'all (especially you Jens)

----- snip ------
You probably will get some compiler warnings for these attempts if
you raise its warning level - if 'y' is a pointer-to-pointer to void,
then y[i] is of type pointer to void, and thus assigning to *y[i] or
*(y[i]) (which is the same, the [] binds more tightly than the de-
reference operator *) would mean you try to assign a value to a void,
which of course isn't allowed.
I'm aware of that... but I intend to typecast my void pointers to other
pointers... But at this stage in the code I do not yet know what
datatype the pointer wil point to. An example could be:

*((double *)y[i]) = double_value; //if it's of type double

I think that is a legal aproach

--- snip -----

I'll let you all know how it went when I get home.
Andreas Vinther
Oct 23 '06 #7
Andreas <an************ *@gmail.comwrot e:
Jens Thoms Toerring skrev:
Andreas Vinther <an************ *@gmail.comwrot e:
I have a small piece of code that compiles but does not perform like I
want it to.
void **y;
int i = 0;
*y = malloc(5 * sizeof(void*));
You assign to something 'y' is pointing to, but since 'y' isn't
initialized things go badly wrong. Moreover, you try to assign to
a void pointer something that points to a set of 5 void pointers -
That is what I want it to do. I want a void pointer that points to 5
other void pointers.
Mmmm, you might think so, but if you really think about it again you may
find that you don't want that. And you may be misled a bit by the malloc()
returning a void pointer and the automatic conversion from void pointers
to any other types of pointers. But you better think about the problem not
in terms of void pointers etc. but instead of some "real" data type. Let's
say you want an array of int pointers. Then you would have

int **x;
x = malloc(5 * sizeof *x); /* or x = malloc(5 * sizeof(int *)); */

and probably wouldn't come up with the idea that 'x' should be an int
pointer but that it must be a pointer-to-pointer to int. I.e. the thing
on the left hand side of the assignment must be a pointer to what you
want allocate memory for, so if you want to allocate memory for a set
of pointers to int you need a pointer-to-pointer to int. And in exactly
the same way you should go about dealing with void pointers and poin-
ters-to-pointers to void. While those may look indistinguishab le at the
first glance they are of different type.
Ofcourse...that 's it.. Stupid me I haven't initialised it yet. So if I add:
void *x
y = &x;
to my original code it should work.
It might work but all for the wrong reasons;-) If you need memory
for a set of values (I avoid the word 'array' here, since an array is
a bit more than just a collection of consecutive values in memory),
be ints, doubles or pointers, the type of a pointer to this "set" is
pointer to the type of the elements of this set. So if you want a set
of void pointers than a pointer to this (what you get from malloc())
must be of type pointer-to-pointer to void, not just void pointer. And
hat's why using

void **y;
y = malloc(5 * sizeof(void *)); /* or y = malloc(5 * sizeof *y); */

is the right way (even if it may be a bit hard to see when you insist
on thinking in terms of void pointers only and not also types).

Moreover, if you would use

void *x;
void **y = &x;
*y = malloc(5 * sizeof(void *));

then using 'y' later is going to be real tricky because 'y' won't be
a pointer-to-pointer to void (as you told in its definition) but a
pointer-to-pointer-to-pointer to void. If you lie to the compiler and
want to get away with it you must know very well what you're doing,
otherwise it will get its revenge;-)
You probably will get some compiler warnings for these attempts if
you raise its warning level - if 'y' is a pointer-to-pointer to void,
then y[i] is of type pointer to void, and thus assigning to *y[i] or
*(y[i]) (which is the same, the [] binds more tightly than the de-
reference operator *) would mean you try to assign a value to a void,
which of course isn't allowed.
I'm aware of that... but I intend to typecast my void pointers to other
pointers... But at this stage in the code I do not yet know what
datatype the pointer wil point to. An example could be:
*((double *)y[i]) = double_value; //if it's of type double
I think that is a legal aproach
While in principle it is (but only if 'y' is really a pointer-to-
pointer to void and not a "triple" pointer) this looks a bit like a
maintenance nightmare in the making. Why insist on using void pointers
etc. when you already know the type of what you're going to store?
Except in special cases I found it to be better for my mental sanity
(as far as any is left;-) to use the correct types wherever possible
and not to obfuscate what's happening by the use of "generic" pointers
and casts. As a rule I try to avoid situations where casts are needed -
often they just show that one hasn't really understood what's going on
and instead of thinking clearly is groping in the dark for some
"solution" that might seems to work (but, alas, often not really does).

Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\______________ ____________ http://toerring.de
Oct 23 '06 #8
On Mon, 2006-10-23 at 16:29 +0300, Papastefanos Serafeim wrote:
"Andreas Vinther" <an************ *@gmail.comwrot e in message
news:45******** *************@d reader1.cyberci ty.dk...
This code doesn't work:
-----------------------

void **y;
int i = 0;

*y = malloc(5 * sizeof(void*));

while (i < 5)
{
*(y+i) = ssGetOutputPort Signal(S,i);
i++;
}

Can anyone tell me why i get segmentation violation?
To me i seems like the code should perform somewhat similar, but I
regulary mess up when using pointers and pointers-to-pointers.

Instead of
*y = malloc(5 * sizeof(void*));
try this
y = (void **)malloc(5 * sizeof(void*));

I think that the typecast is not really needed in C
(but is needed in C++) so I've added it anyway.
Absolutely not. This disguises the fact that you may not have #include'd
<stdlib.h>. (Which, somewhat ironically, may have been the OP's
problem.)

--
Andrew Poelstra <http://www.wpsoftware. net/projects/>

Oct 24 '06 #9
--- snip ----
>I'm aware of that... but I intend to typecast my void pointers to other
pointers... But at this stage in the code I do not yet know what
datatype the pointer wil point to. An example could be:
> *((double *)y[i]) = double_value; //if it's of type double
>I think that is a legal aproach

While in principle it is (but only if 'y' is really a pointer-to-
pointer to void and not a "triple" pointer) this looks a bit like a
maintenance nightmare in the making. Why insist on using void pointers
etc. when you already know the type of what you're going to store?
Except in special cases I found it to be better for my mental sanity
(as far as any is left;-) to use the correct types wherever possible
and not to obfuscate what's happening by the use of "generic" pointers
and casts. As a rule I try to avoid situations where casts are needed -
often they just show that one hasn't really understood what's going on
and instead of thinking clearly is groping in the dark for some
"solution" that might seems to work (but, alas, often not really does).
I see what you mean and I apreciate your help. Like you, I think it's
always best to use datatype specific pointers. But you wrote that I
insist on using void pointers when I already know the datatype I'm going
to point to. That is just it. I do NOT yet know the datatype, as I've
written almost at the top of the text i left in this post. That's why
I'm forced to use void pointers or make similar code sections for every
possible datatype.

The code snip is from a data-logger. The number of variables and their
datatype is set in runtime and not yet know when the program is
compiled. That's why I allocate memory dynamically and use void
pointers. I need to print the values in real-time, and therefore I can't
just log a big hunk of raw data without knowing the individual values
and their sizes in memory.
In hinesight I should have mentioned this ealier or at least been more
specific.

BTW, the code works great now and I thank you all for your help.
PS: I'm sorry for the late reply, but I've just been 10 days to London
and the hotel we stayed in, only allowed people to use the internet on
the hotels computers. The computers were "locked" to a few select tasks
and were 6£/h. Since I'm still a student on a budget, I found the price
ridiculous, and didn't want to fumble around the internet looking for a
www-interface for usenet.
Nov 6 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
1456
by: Pat Mahoney | last post by:
For some reason I am unable to access documents in Javascript. eg - tried to register on a site, and when clicked on register, blank screen came up with this address: "javascript:submit_form('toregister_form')" and "done" in bottom left hand corner. Not being very technical minded - anybody know what I have done wrong,
8
2162
by: Chris Sharman | last post by:
See the bottom of http://www.prestonbridge.pwp.blueyonder.co.uk/index2.htm (4th line of the club officers section). The mark-up's validated html 4 & css, but in ie5.0/Win2000 my surname disappears, leaving just "web author: chris (big space) <myemail.gif>". It's ok (afaik) in other browsers, and even other versions of ie. I tried a lot of variations, and eventually found a workaround (at index.htm) which appears to work, but I'd really...
11
1481
by: alcastle | last post by:
I'm new to C. I have a snippet of code that works, but it's a little off in the output. I'm hoping someone can spot my error(s). I'm reading input from a serial device, and I need to print Hex, which is working but I'm getting unreliable output and have formating issues. Example output: FF00000033 FF00000036 FF00000030 FF00000030 FF00000054 FF0000001A FF0000000F FF00000048 FF00000003 FF0000004A FF00000020 FF00000003 FF00000000...
22
2500
by: rasiel | last post by:
I'm hoping someone can help me out. I'm a researcher in need of developing an automated database and would like to see if someone here is willing to consider putting together for me a simple website. I'm not expecting a freebie of course, I'll pay if you're interested. This is the outline of the project: This would be a website that pulls records from closed eBay auctions and stores them in predefined categories. The data would be...
7
1957
by: David | last post by:
i think i just realized i'm an idiot. again. (not syntactically correct code... just pieces to illustrate) class StateObject { members like socket, receiveBuffer, receiveBufferSize, StringBuilder etc.. }
61
3568
by: warint | last post by:
My lecturer gave us an assignment. He has a very "mature" way of teaching in that he doesn't care whether people show up, whether they do the assignments, or whether they copy other people's work. Furthermore, he doesn't even mark the assignments, but rather gives tips and so forth when going over students' work. To test students' capabilities for the purpose of state exams and qualifications though, he actually sits down with us at a...
3
7846
by: victorporton | last post by:
D.K. is traveling from City A to City B. He can stop at some designated spots only. I am trying to use Dijkstra’s algorithm to determine the “spot-to-spot” path that will get D.K. from City A to the City B in the minimum amount of time. The input in my program is an integer n and the 2D coordinates of n spots. Some assumptions have been made about the physical layout of the problem: 1) All the spots are considered to be in a square of...
3
2348
by: mandanarchi | last post by:
Sub test() Dim myHTTP As MSXML2.xmlhttp Dim myDom As MSXML2.DOMDocument Dim orderno, errormsg, lineerr, lineerrmsg As MSXML2.IXMLDOMNode Dim myxml As String boundary = "-----------------------------29772313742745" myxml = "--" & boundary & vbCrLf & _
3
3927
by: nigelesquire | last post by:
Please help! I'm trying to clone and delete multiple rows with JavaScript. I need two delete buttons that work...! I only have one for now, but it's not working properly, the output count is messing up. Problems:
0
9628
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9464
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10289
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10120
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10061
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7471
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5367
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4031
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3622
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.