473,796 Members | 2,509 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Segfault, please help!

BT
Ok, for a school assignment we have to use a pointer for an array of
ints, intstead of the usual X[i] way, it compiles fine but when i run
it I am getting a seg fault that i can't figure out how to fix. It
occurs at this line:

*d = rand() % 99 + 1

Here is the code for the first part of the program, the line that
causes the seg fault is

#include<stdio. h>
#include<stdlib .h>
#include<time.h >
#define MAXSIZE 11

int main()
{
int DATASIZE = MAXSIZE;
int *narray;

void getdata(int *d, int size);
int largest(int *d, int size);

getdata(narray, DATASIZE);

exit(0);
}

void getdata(int *d, int size)
{
int i;

srand(time(0));
for(i=0; i< size; i++) {
*d = rand() % 99 + 1;
d++;
}
}

Thanks in advance

Mar 29 '06 #1
7 1477
BT wrote:
Ok, for a school assignment we have to use a pointer for an array of
ints, intstead of the usual X[i] way, it compiles fine but when i run
it I am getting a seg fault that i can't figure out how to fix. It
occurs at this line:

*d = rand() % 99 + 1

Here is the code for the first part of the program, the line that
causes the seg fault is

#include<stdio. h>
#include<stdlib .h>
#include<time.h >
#define MAXSIZE 11

int main()
{
int DATASIZE = MAXSIZE;
int *narray;

void getdata(int *d, int size);
int largest(int *d, int size);

getdata(narray, DATASIZE);

exit(0);
}

void getdata(int *d, int size)
{
int i;

srand(time(0));
for(i=0; i< size; i++) {
*d = rand() % 99 + 1;
d++;
}
}

Thanks in advance


Well, i dont want to tell you the whole story because its a school
assignment, but, where did you allocate space for the array called narray?
Eric

Mar 29 '06 #2
"BT" <af****@hotmail .com> writes:
Ok, for a school assignment we have to use a pointer for an array of
ints, intstead of the usual X[i] way, it compiles fine but when i run
it I am getting a seg fault that i can't figure out how to fix. It
occurs at this line:

*d = rand() % 99 + 1

Here is the code for the first part of the program, the line that
causes the seg fault is

#include<stdio. h>
#include<stdlib .h>
#include<time.h >
#define MAXSIZE 11

int main()
Ok, but "int main(void)" is better.
{
int DATASIZE = MAXSIZE;
int *narray;

void getdata(int *d, int size);
int largest(int *d, int size);
Function declarations inside another function are usually considered
poor style. (Nested function *definitions*, of course, are illegal.)
Either move the declarations outside your main function, or re-order
your function definitions so everything is visible where it needs to
be without separate declarations (this doesn't work if you have
recursive calls), or, if your program becomes more complex, put the
function declarations in a header file.
getdata(narray, DATASIZE);
narray is a pointer variable. It needs to point to something. What
is it pointing to here? You want an array of MAXSIZE ints; where do
you allocate the memory for that array?
exit(0);
}

void getdata(int *d, int size)
{
int i;

srand(time(0));
I prefer srand(time(NULL )); it makes it more explicit that the
argument is a pointer.
for(i=0; i< size; i++) {
*d = rand() % 99 + 1;
d++;
}
}


--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Mar 29 '06 #3
BT
Yes I understand about where to put the functions, my professor insists
on us doing it his way, declaring them in main(). Here is what he says
about this: "function prototypes are like data type declarations and
hence, should be declared in the module calling the function". He's
kind of weird about a lot of things.
But about my actual problem, I think i see what you two are getting at.
I need to do something in main after i declare int *narray, so that
enough space in memory is allocated. We have done a little memory
allocation in assembly, but I can't figure out how to do it here. I
tried declaring an int x and then having narray point to it before
getdata, but that didn't work, am i missing something obvious here?

Mar 29 '06 #4
BT
Ok, I think I figured it out, i'm going to need to use malloc(), right?
Thanks for you help again

Mar 29 '06 #5
"BT" <af****@hotmail .com> writes:
Ok, I think I figured it out, i'm going to need to use malloc(), right?
Thanks for you help again


If you had been following this newsgroup for any length of time (which
is generally a good thing to do before posting), you would have seen
dozens of references to <http://cfaj.freeshell. org/google/>.

Read it now.
--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Mar 29 '06 #6
BT wrote:

<snip>

int main()
{
int DATASIZE = MAXSIZE;
int *narray;

void getdata(int *d, int size);
int largest(int *d, int size);

getdata(narray, DATASIZE);

exit(0);
}


<snip>

When I first looked at the code above, I initially 'mentally parsed' it as:

'Wow, he's declaring a /variable/ as a /parameter/ in a function call!'.

*But*, I then saw that this was a function prototype /living/ in non
file-scope, i.e., not placed outside of any function definitions, but within
one.

It's quite unusal to see this, and I never do such a thing - but I think
that's more through habit, than reason, and maybe there's quite some sense
behind using this to restrict scope - *if* the scope of the prototype *is*
restricted to the block/function in which it is declared [which the std
seems to suggest is the case?], and, given that we don't yet have nested
functions in std c, it could be quite useful.

So, irrespective of what the current std says: time to hit the compiler and
see what it/they think! Here's some code then...

#include <stdio.h>

int main(void)
{
void func2(void);

{
void func1(void);

func1();
}

func2();

// See below - problems here?: not happy about func1().
//
func1();

return 0;;
}
void func1(void)
{
// See below - problems here?: not happy about func2().
//
func2();

return;
}
void func2(void)
{
return;
}

---

So, with a few different compilers ...
gcc [v4.0.2]:

[Warning] implicit declaration of func-1/2 (2 from func1(), 1 from main)

[Error] incompatible declaration of func-1/2 (2 from func1(), 1 from
main)

---

bcc 5 [v5.5] [Borland CBuilder]:

[Error] type mismatch of func-1/2

---

lcc [v3.8]

Warnings only

---

MSVC6 and MSVC7:

Compiles ok.
So, the compilers /differ/ rather a lot in their opinions about this!

What do others think? Should there be warnings/errors? If 'yes' to either,
should 'style' [as this is often thought of as being 'bad style'] be
re-thought - seems to me that it could be a reasonable habit to adopt.

P.S. Would be interesting to hear what other compilers make of it too!
--
==============
Not a pedant
==============
Mar 29 '06 #7
"BT" <af****@hotmail .com> wrote in message
news:11******** *************@i 40g2000cwc.goog legroups.com...
Yes I understand about where to put the functions, my professor insists
on us doing it his way, declaring them in main(). Here is what he says
about this: "function prototypes are like data type declarations and
hence, should be declared in the module calling the function". He's
kind of weird about a lot of things.


The quote says "...in the module..."

Putting them above "int main()" would still have them in the module, but would
get them out of the function.

- Bill
Mar 29 '06 #8

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

Similar topics

1
1579
by: Phil Powell | last post by:
Consider these two classes. Class Accepter in placement_classes.inc.php works as a form validation object, and it works like a charm: PHP: // placement_classes.inc.php - THIS ONE WORKS! class Accepter { function Accepter() {
12
3163
by: Nathaniel Echols | last post by:
I've written a function in C to perform protein sequence alignment. This works fine in a standalone C program. I've added the necessary packaging to use it in Python; it returns three strings and an integer. However, as soon as the function is complete, I get a segfault and the interpreter dies. If I run Python interactively, just calling the function causes a segfault. If I'm running a script, I can actually print out the return...
10
2924
by: Arthur J. O'Dwyer | last post by:
I'm seeing a bug at the moment that I can't track down. It's part of a moderately large program, but here is a small program that exhibits the bug on gcc. (The program code follows at the bottom of the message.) The symptom is this: % g++ --version g++ (GCC) 3.2.1 % g++ -W -Wall -pedantic test.cpp
4
1891
by: Jim Strathmeyer | last post by:
Under what circumstances would closing a istream object (such as 'in.close()') SEGFAULT?
3
1667
by: Paul | last post by:
Situation: Running a MPI program that segfaults. Cannot open program up in debugger due to nature of MPI system. Using g++ 3.2.3. Goal: Find out which line it segfaults on; ideally which variable name causes the error. Some kind of error message akin to VC7's "stack corrupted around varname" message would be very nice.
9
29709
by: Bin Lu | last post by:
I keep getting this malloc problem when my program tries to allocate memory for some pointer. The statement is like: rsv_cache = (rsvcache *) malloc (sizeof(rsvcache)); It goes through the function with this statement several times and seems that it has successfully allocated the memory. and then at some iteration, it just gets this segmentation fault. The gdb gives the following message:
7
3763
by: Parahat Melayev | last post by:
I am programming simple TCP server. Some packets causes server to get segmentation fault. Is it possible to handle segmentation fault and log that packet and make server to continue running? If possible can you provide me some example or tutorials please. thanks, parahat melayev
162
6744
by: Richard Heathfield | last post by:
I found something interesting on the Web today, purely by chance. It would be funny if it weren't so sad. Or sad if it weren't so funny. I'm not sure which. http://www.developerdotstar.com/community/node/291 This "teacher of C" demonstrates his prowess with a masterful display of incompetence in a 200-line program that travels as swiftly as possible to Segfault City.
49
1737
by: comp.lang.php | last post by:
/** * Class for grayscaling image * * @author Phil Powell * @version 1.2.1 * @package IMAGE_CATALOG::IMAGE */ class ImageGrayscaleGenerator extends ImageResizeComponents { /
1
1203
by: dikanst | last post by:
I'm getting a segmentation fault in one of my functions, which basically adds an employee structure to an array of employee pointers. Here's a condensed version of my C program: typedef struct { char *firstName; ...... ...... } Employee; void hireEmployee(Employee *array)
0
10456
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
10012
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9052
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7548
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
6788
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5442
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...
0
5575
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3731
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2926
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.