473,599 Members | 3,118 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A NULL pointer changed after returned?

fix
Hi all,
I am new to C and I just started to program for a homework.
I included my code down there.
It is a fraction "class". I declared the Fraction struct, tried to
create some invalid fraction, with denominator zero.
A Fraction is created by the newFraction() function, and which in turns
call normalize() function to simplify it, but before, the normalize()
function will do a check, if the denominator is zero, it will give a
error by returning a NULL.
Everything works fine for a normal fraction, e.g. 3/4, 5/4, but if I
give a "4/0" to the function, it is frustrating.
In the normalize function, I am sure it is set to NULL, but back to
newFraction, it changed back to 4/0. But if I give a fraction that could
be simplified, such as 6/8, it is simpified and returned as 3/4 with
no problem.
Please help!
fix.

Fraction.c:
#include "Fraction.h "
void Case1c()
{
printFraction(n ewFraction(0,4) );printf("\n");
printFraction(n ewFraction(4,0) );printf("\n");
printFraction(n ewFraction(0,0) );printf("\n");
}

int main(void)
{
printf("Case 1c:\n");Case1c( );
return 0;
}

Fraction.h:
#include <stdio.h>

typedef struct {
int sign;
int numerator;
int denominator;
} Fraction;

int signOf(int number){
if (number < 0)
return -1;
else
return 1;
}

int gcd(int num1, int num2){
if (num1 < num2)
return gcd(num2, num1);
else
if ((num1 % num2) == 0)
return num2;
else
return gcd(num2, num1 % num2);
}

void normalize(Fract ion *fr){
int factor;
if (fr->denominator == 0) // Invalid function
{
fr = NULL; // set it to NULL and return

printf("Set fr = NULL\n");
if (fr!=NULL)
printf("Not null");
else
printf("null");
return;
}
// Take the signs form the numerator and denominator to the sign variable
fr->sign *= signOf(fr->numerator);
fr->sign *= signOf(fr->denominator) ;

// Absolute the numerator and denominator
fr->numerator *= signOf(fr->numerator);
fr->denominator *= signOf(fr->denominator) ;

if (fr->numerator == 0)
{ // If the numerator is 0, simplify it to 0/1
fr->denominator = 1;
fr->sign = 1;
}
else
{ // Find the gcd of the numerator and denominator, divide them by the gcd
factor = gcd(fr->numerator, fr->denominator) ;
fr->numerator /= factor;
fr->denominator /= factor;
}
}
Fraction newFraction(int num, int den)
{
Fraction fr;
Fraction *frp;

fr.numerator = num;
fr.denominator = den;
fr.sign = 1;
frp = &fr;
normalize(frp);
if (frp!=NULL)
printf("Not null");
else
printf("null");

return fr;
}
void printFraction(F raction fr)
{
if (&fr == NULL)
printf("Invalid fraction");

if (fr.sign == -1)
printf("-");
printf("%i/%i", fr.numerator, fr.denominator) ;
}

Nov 14 '05 #1
16 1911
fix <fi*@here.com > writes:
void normalize(Fract ion *fr){
int factor;
if (fr->denominator == 0) // Invalid function
{
fr = NULL; // set it to NULL and return

printf("Set fr = NULL\n");
if (fr!=NULL)
printf("Not null");
else
printf("null");
return;


This is in the FAQ.

4.8: I have a function which accepts, and is supposed to initialize,
a pointer:

void f(int *ip)
{
static int dummy = 5;
ip = &dummy;
}

But when I call it like this:

int *ip;
f(ip);

the pointer in the caller remains unchanged.

A: Are you sure the function initialized what you thought it did?
Remember that arguments in C are passed by value. The called
function altered only the passed copy of the pointer. You'll
either want to pass the address of the pointer (the function
will end up accepting a pointer-to-a-pointer), or have the
function return the pointer.

See also questions 4.9 and 4.11.
--
char a[]="\n .CJacehknorstu" ;int putchar(int);in t main(void){unsi gned long b[]
={0x67dffdff,0x 9aa9aa6a,0xa77f fda9,0x7da6aa6a ,0xa67f6aaa,0xa a9aa9f6,0x1f6}, *p=
b,x,i=24;for(;p +=!*p;*p/=4)switch(x=*p& 3)case 0:{return 0;for(p--;i--;i--)case
2:{i++;if(1)bre ak;else default:continu e;if(0)case 1:putchar(a[i&15]);break;}}}
Nov 14 '05 #2

# void normalize(Fract ion *fr){

This copies the Fraction* parameter value into a local variable fr.
All changes to fr itself are to this local variable and not propagated
back to the caller. It's changes to *fr (or fr->...) that are visible
to the caller.

You can instead do something like
Fraction *normalize(Frac tion *fr) {
...
return fr;
}
which propagates changes back to the caller as the function yield.
You can then call
frp = normalize(frp);
if (frp!=NULL)
printf("Not null");
else
printf("null");

# frp = &fr;
# normalize(frp);

This passes the address of the structure, not the address of pointer
variable to the structure.

--
Derk Gwen http://derkgwen.250free.com/html/index.html
I hope it feels so good to be right. There's nothing more
exhilirating pointing out the shortcomings of others, is there?
Nov 14 '05 #3
In 'comp.lang.c', fix <fi*@here.com > wrote:
Fraction.c:
#include "Fraction.h "

<snipped>

First of all, I highly recommend that you change your code organization. It's
a very bad idea to have code included in a .h. I suggest a very common
approach as follow:

/* main.c */
#include "Fraction.h "
#include <stdio.h>

/* macros =============== =============== =============== =============== == */
/* constants =============== =============== =============== ============== */
/* types =============== =============== =============== =============== === */
/* structures =============== =============== =============== ============= */
/* private variables =============== =============== =============== ====== */
/* private functions =============== =============== =============== ====== */

static void Case1c (void)
{
printFraction (newFraction (0, 4));
printf ("\n");
printFraction (newFraction (4, 0));
printf ("\n");
printFraction (newFraction (0, 0));
printf ("\n");
}

/* entry point =============== =============== =============== ============ */

int main (void)
{
printf ("Case 1c:\n");
Case1c ();
return 0;
}

/* public variables =============== =============== =============== ======= */

/* fraction.h */
#ifndef H_FRACTION
#define H_FRACTION
/* macros =============== =============== =============== =============== == */
/* constants =============== =============== =============== ============== */
/* types =============== =============== =============== =============== === */
/* structures =============== =============== =============== ============= */

typedef struct
{
int sign;
int numerator;
int denominator;
}
Fraction;

/* internal public functions =============== =============== ============= */
/* entry points =============== =============== =============== =========== */

Fraction newFraction (int num, int den);
void printFraction (Fraction fr);

/* public variables =============== =============== =============== ======= */

#endif /* guard */

/* fraction.c */
#include <stdio.h>
#include "fraction.h "

/* macros =============== =============== =============== =============== == */
/* constants =============== =============== =============== ============== */
/* types =============== =============== =============== =============== === */
/* structures =============== =============== =============== ============= */
/* private variables =============== =============== =============== ====== */
/* private functions =============== =============== =============== ====== */

static int signOf (int number)
{
if (number < 0)
return -1;
else
return 1;
}

static int gcd (int num1, int num2)
{
if (num1 < num2)
return gcd (num2, num1);
else if ((num1 % num2) == 0)
return num2;
else
return gcd (num2, num1 % num2);
}

static void normalize (Fraction * fr)
{
int factor;
if (fr->denominator == 0) /* Invalid function */
{
fr = NULL; /* set it to NULL and return */

printf ("Set fr = NULL\n");
if (fr != NULL)
printf ("Not null");
else
printf ("null");
return;
}
/* Take the signs form the numerator and denominator to the sign variable
*/
fr->sign *= signOf (fr->numerator);
fr->sign *= signOf (fr->denominator) ;

/* Absolute the numerator and denominator */
fr->numerator *= signOf (fr->numerator);
fr->denominator *= signOf (fr->denominator) ;

if (fr->numerator == 0)
{ /* If the numerator is 0, simplify it to 0/1
*/
fr->denominator = 1;
fr->sign = 1;
}
else
{ /* Find the gcd of the numerator and
denominator, divide them by the gcd */
factor = gcd (fr->numerator, fr->denominator) ;
fr->numerator /= factor;
fr->denominator /= factor;
}
}

/* internal public functions =============== =============== ============= */
/* entry points =============== =============== =============== =========== */

Fraction newFraction (int num, int den)
{
Fraction fr;
Fraction *frp;

fr.numerator = num;
fr.denominator = den;
fr.sign = 1;
frp = &fr;
normalize (frp);
if (frp != NULL)
printf ("Not null");
else
printf ("null");

return fr;
}

void printFraction (Fraction fr)
{
if (&fr == NULL)
printf ("Invalid fraction");

if (fr.sign == -1)
printf ("-");
printf ("%i/%i", fr.numerator, fr.denominator) ;
}

/* public variables =============== =============== =============== ======= */

Note that I have no changed your code.

--
-ed- em**********@no os.fr [remove YOURBRA before answering me]
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-reference: http://www.dinkumware.com/manuals/reader.aspx?lib=cpp
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 14 '05 #4
fix


Derk Gwen wrote:
# void normalize(Fract ion *fr){

This copies the Fraction* parameter value into a local variable fr.
All changes to fr itself are to this local variable and not propagated
back to the caller. It's changes to *fr (or fr->...) that are visible
to the caller.

You can instead do something like
Fraction *normalize(Frac tion *fr) {
...
return fr;
}
which propagates changes back to the caller as the function yield.
You can then call
frp = normalize(frp);
if (frp!=NULL)
printf("Not null");
else
printf("null");

# frp = &fr;
# normalize(frp);

This passes the address of the structure, not the address of pointer
variable to the structure.

--
Derk Gwen http://derkgwen.250free.com/html/index.html
I hope it feels so good to be right. There's nothing more
exhilirating pointing out the shortcomings of others, is there?

Yup thanks!

Nov 14 '05 #5
fix


Ben Pfaff wrote:
fix <fi*@here.com > writes:

void normalize(Fract ion *fr){
int factor;
if (fr->denominator == 0) // Invalid function
{
fr = NULL; // set it to NULL and return

printf("Set fr = NULL\n");
if (fr!=NULL)
printf("Not null");
else
printf("null");
return;

This is in the FAQ.

4.8: I have a function which accepts, and is supposed to initialize,
a pointer:

void f(int *ip)
{
static int dummy = 5;
ip = &dummy;
}

But when I call it like this:

int *ip;
f(ip);

the pointer in the caller remains unchanged.

A: Are you sure the function initialized what you thought it did?
Remember that arguments in C are passed by value. The called
function altered only the passed copy of the pointer. You'll
either want to pass the address of the pointer (the function
will end up accepting a pointer-to-a-pointer), or have the
function return the pointer.

See also questions 4.9 and 4.11.


Ah...... I got you, so that means if I change the content in the struct,
i.e. changing the signs, denom and numerators, the pointer hasn't
changed, but if I point it to NULL, I am actually changing the pointer
so it reverts to the original value outside the function body.
If I am to return a pointer, I am curious that if I return a pointer to
a variable created inside the function, will the variable be garbage
collected but the pointer still pointing to that? I was learning Java
last semester and I have no trouble with pointers.......

Nov 14 '05 #6
fix
Is this the order? Does C have any privacy (private
functions/variables)? And what is entry point?
Thanks.
/* macros =============== =============== =============== =============== == */
/* constants =============== =============== =============== ============== */
/* types =============== =============== =============== =============== === */
/* structures =============== =============== =============== ============= */
/* private variables =============== =============== =============== ====== */
/* private functions =============== =============== =============== ====== */
/* entry point =============== =============== =============== ============ */
/* public variables =============== =============== =============== ======= */

Nov 14 '05 #7
In 'comp.lang.c', fix <fi*@here.com > wrote:
Is this the order?
It's not /the/ order, it's mine, but actually, my experience has shown to me
that's it's hard to have another one!
Does C have any privacy (private
functions/variables)?
sure, by the use of the 'static' word.
/* macros =============== =============== =============== =============== == */
/* constants =============== =============== =============== ============== */
/* types =============== =============== =============== =============== === */
/* structures =============== =============== =============== ============= */
/* private variables =============== =============== =============== ====== */
/* private functions =============== =============== =============== ====== */
/* entry point =============== =============== =============== ============ */
/* public variables =============== =============== =============== ======= */ And what is entry point?


This list was retrieved from a 'main.c' which is the source file that holds
the main() function. This function being by-definition the top-level function
of the application, it is also the unique entry point (the first entry) of
the module.

--
-ed- em**********@no os.fr [remove YOURBRA before answering me]
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-reference: http://www.dinkumware.com/manuals/reader.aspx?lib=cpp
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 14 '05 #8
fix <fi*@here.com > writes:
Ah...... I got you, so that means if I change the content in the
struct, i.e. changing the signs, denom and numerators, the pointer
hasn't changed, but if I point it to NULL, I am actually changing the
pointer so it reverts to the original value outside the function body.
If I am to return a pointer, I am curious that if I return a pointer
to a variable created inside the function, will the variable be
garbage collected but the pointer still pointing to that? I was
learning Java last semester and I have no trouble with pointers.......


C doesn't have garbage collection.

You really need to read the FAQ. This is also a FAQ.

7.5a: I have a function that is supposed to return a string, but when
it returns to its caller, the returned string is garbage.

A: Make sure that the pointed-to memory is properly allocated.
For example, make sure you have *not* done something like

char *itoa(int n)
{
char retbuf[20]; /* WRONG */
sprintf(retbuf, "%d", n);
return retbuf; /* WRONG */
}

One fix (which is imperfect, especially if the function in
question is called recursively, or if several of its return
values are needed simultaneously) would be to declare the return
buffer as

static char retbuf[20];

See also questions 7.5b, 12.21, and 20.1.

References: ISO Sec. 6.1.2.4.
--
"Given that computing power increases exponentially with time,
algorithms with exponential or better O-notations
are actually linear with a large constant."
--Mike Lee
Nov 14 '05 #9

"fix" <fi*@here.com > wrote in message news:
Is this the order? Does C have any privacy (private
functions/variables)? And what is entry point?
Thanks.

The main unit of organisation for C is the file.
Typically a file will contain either one complex function, or a list of
related functions.
For example, my BASIC interpreter has a single, very complex function,
basic(const char *script), which allows a BASIC script to be run.
Needless to say there are many sub-functions which that function calls, for
instance there is a function to calculate the value of an algebraic
expression, a function to print output, a function to execute a conditional
jump. However I don't want the user to call any of these functions directly,
so they are private to that file, or static. There is only one entry point,
the basic() function itself.
There are also private variables. For instnace the first thing I do is read
all the line numbers and store them in a global array for fast access.
Obviously I don't want anyone messing with that array either, so these
variables are also declared static, or local to that file.
Nov 14 '05 #10

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

Similar topics

7
20342
by: Pablo J Royo | last post by:
Hello: i have a function that reads a file as an argument and returns a reference to an object that contains some information obtained from the file: FData &ReadFile(string FilePath); But , for example, when the file doesnt exists, i should not return any reference to a bad constructed object, so i need something as a NULL reference object. I suppose i could return a pointer instead, but i have some code written with references which...
14
2694
by: William Ahern | last post by:
is this legal: FILE *func(void) { extern int errno; return (errno = EINVAL, NULL); } my compiler (gcc 2.9.x on openbsd) is complaining that i'm returning a pointer from int w/o a cast. gcc 3.x on linux, however, never made a peep
102
5950
by: junky_fellow | last post by:
Can 0x0 be a valid virtual address in the address space of an application ? If it is valid, then the location pointed by a NULL pointer is also valid and application should not receive "SIGSEGV" ( i am talking of unix machine ) while trying to read that location. Then how can i distinguish between a NULL pointer and an invalid location ? Is this essential that NULL pointer should not point to any of the location in the virtual address...
99
5112
by: Mikhail Teterin | last post by:
Hello! Consider the following simple accessor function: typedef struct { int i; char name; } MY_TYPE; const char *
64
3889
by: yossi.kreinin | last post by:
Hi! There is a system where 0x0 is a valid address, but 0xffffffff isn't. How can null pointers be treated by a compiler (besides the typical "solution" of still using 0x0 for "null")? - AFAIK C allows "null pointers" to be represented differently then "all bits 0". Is this correct? - AFAIK I can't `#define NULL 0x10000' since `void* p=0;' should work just like `void* p=NULL'. Is this correct?
12
2420
by: Luca | last post by:
I have 2 questions: 1. Which one is the best: Returning member variables of the class by const ref or returning by pointer? e.g.: Employee* GetEmployee() const; Employee& GetEmployee() const;
3
2090
by: Alexander Behnke | last post by:
Hello, I am currently facing a problem with a calloc function call which returns a NULL pointer while in a debugging environment. If I start the same executable from the shell (not via the debugger) a valid pointer is returned. The call stack looks like this: FlowPRESS.exe!strcat() Line 169 Asm
27
3108
by: Terry | last post by:
I am getting the following warning for the below function. I understand what it means but how do I handle a null reference? Then how do I pass the resulting value? Regards Warning 1 Function 'Dec2hms' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
9
3794
by: Francois Grieu | last post by:
When running the following code under MinGW, I get realloc(p,0) returned NULL Is that a non-conformance? TIA, Francois Grieu #include <stdio.h> #include <stdlib.h>
0
7992
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
7904
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
8400
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
8051
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,...
0
8267
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
6725
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...
0
5438
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
3898
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
3940
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.