473,804 Members | 2,164 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

segfault w/ block, but not file scope

Hi.

In the snippet of code below, I'm trying to understand why when the

struct dirent ** namelist

is declared with "file" scope, I don't have a problem freeing the
allocated memory. But when the struct is declared in main (block scope)
it will segfault when passing namelist to freeFileNames() .

Since this seems to be just a matter of my understanding scope and
pointer parameter passing better, I only included what thought to be
relevant code. I'll happily provide compilable code if deemed necessary.

Please see commented lines:
struct dirent **namelist; /* file scope works */

int main(void)
{
/* struct dirent **namelist */ /* block scope doesn't work */
int n;

n = getFileNames(H5 DIR, namelist); /* included from mylib.h */
freeFileNames(n amelist, n); /* included from mylib.h */

return 0;
}
Thank you very much for your comments,
Dieter
Jan 6 '06
165 6931
On 2006-01-08, Joseph Dionne <jd*****@hotmai l.com> wrote:

It is just as amusing as you assertion, backed by no well known authority of
the c language specification, that c does not support pass by reference.

Your continued reference to 'object' during replies proves my assertions --
recent OOP development (decades ago implemented recent, I mean) have
obfuscated the meaning of "pass by reference". I suspect this is due mostly
to the declining software knowledge, and skills, that has again raised the
acclaim and praise for "garbage collection" languages.

Show me any authority that shares you "opinion" that c does not "pass by
reference".


Arguments are always passed by value in C function calls, meaning that local copies of the values of the arguments are passed to the routines. Changes that you may make to the arguments in the function are made only to the local copies of the arguments. Passing by reference means you can change the value of the argument outside the scope of your function, which doesn't happen. If you have a function like: void foo(char *a) you cannot change the value of the argument, but you can change the content of the memory that the address points to. Pass-by-xxxx refers to the way the arguments are passed to the function and, in C, it's always by value. The fact that the function can change the value at the address your pointer points to is just a side-effect and has nothing to do with how the arguments are passed.

I don't remember exatly and I don't have a copy of the book right now, but I think K&R says that arguments are always passed by value in C function calls. No one will say anything about pass by reference because there's no such thing in C.

JAVA is a languae where everything's a reference. JAVA also passes the arguments to functions by value *only* (if you don't believe me check the documentation), but you can change the elements of an array that's passed to a function and it doesn't mean that array was passed by reference.

If I remember correctly in C++:

void foo(int &i) {
i=2;
}
....
int i=0;
foo(i)
=> i=2

type is int, you send int, int is changed in the function. That's pass by reference.

in C:

void foo(int *i) {
*i=2;
}
....
int i=0;
foo(&i);
=> i=2

type is int, you send a pointer to int, int is changed in the function. The functions doesn't tell you that it needs an int to change an int. It tells you it needs a pointer to int that it can't change.
Although you can consider &int a reference to an int, the function doesn't ask for a reference but for a type which is called "pointer to int" and what you send is the value of a pointer to int type.

--
Ioan - Ciprian Tandau
ta****@freeshel l.org
Jan 8 '06 #81
Nelu wrote:
On 2006-01-08, Joseph Dionne <jd*****@hotmai l.com> wrote:
It is just as amusing as you assertion, backed by no well known authority of
the c language specification, that c does not support pass by reference.

Your continued reference to 'object' during replies proves my assertions --
recent OOP development (decades ago implemented recent, I mean) have
obfuscated the meaning of "pass by reference". I suspect this is due mostly
to the declining software knowledge, and skills, that has again raised the
acclaim and praise for "garbage collection" languages.

Show me any authority that shares you "opinion" that c does not "pass by
reference".

Arguments are always passed by value in C function calls, meaning that local copies of the values of the arguments are passed to the routines. Changes that you may make to the arguments in the function are made only to the local copies of the arguments. Passing by reference means you can change the value of the argument outside the scope of your function, which doesn't happen. If you have a function like: void foo(char *a) you cannot change the value of the argument, but you can change the content of the memory that the address points to. Pass-by-xxxx refers to the way the arguments are passed to the function and, in C, it's always by value. The fact that the function can change the value at the address your pointer points to is just a side-effect and has nothing to do with how the arguments are passed.

I don't remember exatly and I don't have a copy of the book right now, but I think K&R says that arguments are always passed by value in C function calls. No one will say anything about pass by reference because there's no such thing in C.

JAVA is a languae where everything's a reference. JAVA also passes the arguments to functions by value *only* (if you don't believe me check the documentation), but you can change the elements of an array that's passed to a function and it doesn't mean that array was passed by reference.

If I remember correctly in C++:

void foo(int &i) {
i=2;
}
...
int i=0;
foo(i)
=> i=2

type is int, you send int, int is changed in the function. That's pass by reference.


It is pass by reference *because* i can and is modified. So to is i modified
in c, only the syntax has been changed to protect the innocent?
in C:

void foo(int *i) {
*i=2;
}
...
int i=0;
foo(&i);
=> i=2

type is int, you send a pointer to int, int is changed in the function. The functions doesn't tell you that it needs an int to change an int. It tells you it needs a pointer to int that it can't change.
Although you can consider &int a reference to an int, the function doesn't ask for a reference but for a type which is called "pointer to int" and what you send is the value of a pointer to int type.

Jan 8 '06 #82
On 2006-01-08, Nelu <ta****@freeshe ll.org> wrote:
<something about pass by reference>

Really sorry for the last post. I switched, recently,
from google groups to slrn and I didn't know it
knows not how to cut long lines. It's the first time
I use it...
I'll remember this for the future.
Also, from slrn it's easier to understand why keeping
some context when repying is useful :-).

--
Ioan - Ciprian Tandau
ta****@freeshel l.org
Jan 8 '06 #83
On 2006-01-08, Joseph Dionne <jd*****@hotmai l.com> wrote:
It is pass by reference *because* i can and is modified. So to is i modified
in c, only the syntax has been changed to protect the innocent?

In the C function I posted &i is the argument not i.
The i outside the function is modified but that i is not
the same as the one in the function. Modifying the i in the function
has no effect on the i outside the function. The i outside the function
is modified by modifying something different in the function,
i.e. *i which is not the variable you passed to the function.
Even if this is a mechanism that allows for the implementation of
pass-by-reference, it's not the same thing. You can say that
pass-by-reference can hide a pass-by-value but not that a pass-by-value
hides a pass-by-reference (otherwise it means that making a change
to the copy automatically changes the original, which doesnt't happen),
so they are not the same thing.
--
Ioan - Ciprian Tandau
ta****@freeshel l.org
Jan 8 '06 #84
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Joseph Dionne wrote:
Keith Thompson wrote:
Joseph Dionne <jd*****@hotmai l.com> writes:
[...]
No way! '&' is a bit wise logical AND, to get the contents of a
pointer, one codes it as "&pointer" not "& pointer" which will
generate an error.

Fortunately, the C language has rules that permit implementations to
distinguish between a "binary bitwise logical and" operator and a "unary
prefix address of" operator, even if they both share the same translation token.

Are you telling me that

{
int a = 7, b = 4, *c;

c = & a;
}

will result in a syntax error? I think not.
I'm beginning to suspect that you may be a deliberate troll. [snip] The unary "&" operator doesn't yield the contents of a pointer; it
yields the address of an object.
[snip]
It is just as amusing as you assertion, backed by no well known
authority of the c language specification, that c does not support pass
by reference.
- From the C 9989-1999 proposed standard (and, IIRC, from previous C standards,
all the way back to K&R C and forward to the accepted C'99 standard)

6.5.2.2 Function Calls

4 An argument may be an expression of any object type. In preparing for a
call to the function, the arguments are evaluated, and each parameter is
assigned the value of the corresponding argument.

Sounds like the standard says "pass by value" to me. And it doesn't say "pass
by reference" anywhere in it.

Perhaps you've become fooled by the mechanics of pointer variables. Passing
pointers to functions can /look/ like "pass by reference" even though it is
actually "pass by value". Consider the following code fragments

void foo(int *a)
{
/* body of function foo */
*a = 8;
}

void bar(void)
{
int q = 6;
foo(&q);
}

In the above functions, you might think that "pass by reference" is being
used, but it is not.

In the context of the function call to foo() ( "foo(&q);" )
q is an object of type int.

&q is another object (a temporary one crafted by the language to serve as a
vehicle to pass data to a function) of type "pointer to int"

q has a value of 6
&q has a value of a pointer to q

Function foo() will receive the /value/ of the temporary object &q. It does
not receive a /reference/ to q (or even to the temporary &q). It's as if that
original function had been coded as
void bar(void)
{
int q = 6;
int *pq = &q;

foo(pq); /* still pass by value, just value of pq */
}
Your continued reference to 'object' during replies proves my assertions
-- recent OOP development (decades ago implemented recent, I mean)
Well, Keith is using the word "object" in the same manner (and apparently with
the same meaning) as the C standard (and it's predecessor documents) does.

- From the C 9989-1999 proposed standard document section 3 ("Terms, definitions
and Symbols"):

3.14
object
region of data storage in the execution environment, the contents of which
can represent values

C 9989-1999 goes on using the word "object" throughout it's text, in exactly
the context that Keith has used it. I'm afraid that you don't have any choice
but to accept this terminology, recent OOP usage or not.
have
obfuscated the meaning of "pass by reference". I suspect this is due
mostly to the declining software knowledge, and skills, that has again
raised the acclaim and praise for "garbage collection" languages.

Show me any authority that shares you "opinion" that c does not "pass by
reference".


I think that the C standards should be sufficient authority to confirm Keith's
"opinion".

- --
Lew Pitcher

Master Codewright & JOAT-in-training | GPG public key available on request
Registered Linux User #112576 (http://counter.li.org/)
Slackware - Because I know what I'm doing.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.7 (GNU/Linux)

iD8DBQFDwKNjagV FX4UWr64RAvDrAJ 9JRNN/WaXaq0J4O4egJiu RwCtNiQCeN/y5
ou4vGFXt3wBzmmU DCwCz/+I=
=p6kP
-----END PGP SIGNATURE-----
Jan 8 '06 #85
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Nelu wrote:
On 2006-01-08, Joseph Dionne <jd*****@hotmai l.com> wrote:
It is just as amusing as you assertion, backed by no well known authority of
the c language specification, that c does not support pass by reference.

Your continued reference to 'object' during replies proves my assertions --
recent OOP development (decades ago implemented recent, I mean) have
obfuscated the meaning of "pass by reference". I suspect this is due mostly
to the declining software knowledge, and skills, that has again raised the
acclaim and praise for "garbage collection" languages.

Show me any authority that shares you "opinion" that c does not "pass by
reference".

Arguments are always passed by value in C function calls, meaning that
local copies of the values of the arguments are passed to the routines.

[snip] I don't remember exatly and I don't have a copy of the book right now,
but I think K&R says that arguments are always passed by value in C function
calls. No one will say anything about pass by reference because there's no

such thing in C.

You are correct.

K&R C (First edition) says

"In preparing for the call to a function, a copy is made of each actual
parameter; thus, all argument-passing in C is strictly by value."

(Appendix A: C Reference Manual, "The C Programming Language", Brian W.
Kernighan & Dennis M. Ritchie, Copyright 1978 by Bell Telephone Laboratories,
Incorporated, Published by Prentice-Hall, Inc.)
[snip]

- --
Lew Pitcher

Master Codewright & JOAT-in-training | GPG public key available on request
Registered Linux User #112576 (http://counter.li.org/)
Slackware - Because I know what I'm doing.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.7 (GNU/Linux)

iD8DBQFDwKVVagV FX4UWr64RAv9TAK C564WPjQqJmYXWa CQkRp3X3j3vCQCf XWPG
Jbi1XWwB3A3vCNa 0SQTfGac=
=kjjN
-----END PGP SIGNATURE-----
Jan 8 '06 #86
Nelu wrote:
On 2006-01-08, Joseph Dionne <jd*****@hotmai l.com> wrote:
It is pass by reference *because* i can and is modified. So to is i modified
in c, only the syntax has been changed to protect the innocent?


In the C function I posted &i is the argument not i.
The i outside the function is modified but that i is not
the same as the one in the function. Modifying the i in the function
has no effect on the i outside the function. The i outside the function
is modified by modifying something different in the function,
i.e. *i which is not the variable you passed to the function.
Even if this is a mechanism that allows for the implementation of
pass-by-reference, it's not the same thing. You can say that
pass-by-reference can hide a pass-by-value but not that a pass-by-value
hides a pass-by-reference (otherwise it means that making a change
to the copy automatically changes the original, which doesnt't happen),
so they are not the same thing.


The syntax difference in c++ is sexier, easier for those new to the language
to implement with less debug time, but is nothing more than using the
principle of passing a reference to a variable in order to modify the original
memory contents.

A custom c pre processor can simulate the same syntax, even support both
syntax, but that would most likely introduce more developer coding bugs not
less as desired.

I will only agree to disagree with the assertions made that "pass by
reference" is more about language syntax than language capability. Pass by
reference as a principle is well defined, and c complies with the definition.

Now this *troll* needs to get on with real world work, as some suggest I lack.

Cheers to all, the discussion was enlightening.
Jan 8 '06 #87
Joseph Dionne said:
A pointer can be passed by value,
Yes, I know. In fact, that is the only way it can be passed directly as a
function argument.
it that address of the memory storing an
address to memory used for "data", or passed by reference to "hide" it
memory address from the function called.
No, it can't be passed by reference.

For example, using your allocstr() function called by value;

{
char *t;

allocstr(t,10);
}

Will not have the desired result,
Gosh.
char pointer t will remain pointing at
it
original ram address both before and after the call to allocstr().
Is that right?
However, I can pass a reference to t, syntactically &s, that WILL have the
desired result.
No, you can't, because it's the wrong type, and in any case passing *a*
reference is not the same as passing *by* reference.

Note for terminology bigots: "The technical term used in programming
languags for an address of a location in memory is a /reference/ because it
/refers/ to a memory location." - Bruce Maclennan, "Principles of
Programming Languages", p57). The C Standard does not appear to use the
word in this way, however; at least, neither the C89 draft nor N869.
(Searching a PDF is like searching your spam for email, so I didn't look in
C99 Final.)

Further "by value" passing of pointers is strlen() implementation, for
example;

int strlen(char *s)
If that's how you implement strlen, remind me not to use your
implementation.
{
int ii;

for(ii=0;*s;ii+ +);


Undefined behaviour when (not if) ii overflows. It will overflow for all
strings except the empty string.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jan 8 '06 #88
Keith Thompson said:
Then we need to make it very clear to J Random Newbie that C doesn't
support pass by reference as a languag construct.
Right.
Don't say that the
"*" means pass by reference; say that the "*" means you're passing a
pointer value, which can be used to do the equivalent of pass by
reference.
To a newbie, the two statements can seem equivalent, especially if he
doesn't know what "pass by reference" is and has to go and look it up. Why
use the phrase at all, when it doesn't add any value?
Until J Random Newbie is able to hold that entire complex
thought in his head, he's not going to be able to be an effective C
programmer.
We can ease that journey by not giving him useless junk to remember.
Pass by reference is a very common and useful programming technique,
one that C supports quite well (though arguably a little more clumsily
than some other languages do).


I know what you're saying, but I think that's an own-foot-shooting way to
say it.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jan 8 '06 #89
Joseph Dionne wrote:
[...]

Show me any authority that shares you "opinion" that c does not "pass by
reference".


"In preparing for the call to a function, a copy is made of each
argument; all argument-passing is strictly by value."
The C Programming Language, Second edition.
Brian W. Kernighan, Dennis M. Ritchie
A7.3.2 Function Calls (pages 201, 202)
Jan 8 '06 #90

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

Similar topics

699
34287
by: mike420 | last post by:
I think everyone who used Python will agree that its syntax is the best thing going for it. It is very readable and easy for everyone to learn. But, Python does not a have very good macro capabilities, unfortunately. I'd like to know if it may be possible to add a powerful macro system to Python, while keeping its amazing syntax, and if it could be possible to add Pythonistic syntax to Lisp or Scheme, while keeping all of the...
18
3466
by: Minti | last post by:
I was reading some text and I came across the following snippet switch('5') { int x = 123; case '5': printf("The value of x %d\n", x); break; }
6
2484
by: Code Raptor | last post by:
Folks, I am hitting a segfault while free()ing allocated memory - to make it short, I have a linked list, which I try to free node-by-node. While free()ing the 28th node (of total 40), I hit a segfault. This is legacy code. I tried debugging this problem, and am not able to come up with a valid reason for this. Following function is being used to free: void DBFreePUF (DBPUFRec *userp) {
12
2730
by: G Patel | last post by:
I've seen some code with extern modifiers in front of variables declared inside blocks. Are these purely definitions (no definition) or are they definitions with static duration but external linkage? Not much on this in the FAQ or tutorials.
7
7720
by: seamoon | last post by:
Hi, I'm doing a simple compiler with C as a target language. My language uses the possibility to declare variables anywhere in a block with scope to the end of the block. As I remembered it this would be easily translated to C, but it seems variable declaration is only possible in the beginning of a block in C. Any suggestions how to get around this?
7
1478
by: BT | last post by:
Ok, for a school assignment we have to use a pointer for an array of ints, intstead of the usual X 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
8
3209
by: nobrow | last post by:
Okay ... Im out of practice. Is it not possible to have a 2D array where each column is of a different type, say an int and a struct*? The following seg faults for me and I cant figure out what I need to change. Thanks. #include <malloc.h> #include <string.h>
24
2675
by: Neal Becker | last post by:
One thing I sometimes miss, which is common in some other languages (c++), is idea of block scope. It would be useful to have variables that did not outlive their block, primarily to avoid name clashes. This also leads to more readable code. I wonder if this has been discussed?
10
1879
by: somebody | last post by:
There are two files below named search.c and search.h. In the for loop in search.c, the for loop never exits, even if mystruct.field1 has no match. Instead of exiting the for loop it keeps going until it segfaults. This seems to be related to the strcmp with the NULL value. There are 2 comments below that indicate the segfaults. I guess the question is, when there is no match, how to I detect that and return without a segfault?
0
9714
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
9594
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
10600
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
10350
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
10351
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
10096
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
9174
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
7638
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...
2
3834
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.