473,796 Members | 2,628 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 6914
Jordan Abel wrote:
On 2006-01-10, aegis <ae***@mad.scie ntist.com> wrote:
My original post was in reply to your opposition of the claim that C
does not support 'pass by reference'. I thought it was clear that this
was about a mechanism of the language and not something you implement
with the language. If instead, you mean to say the value of a pointer
object can also be called a reference and that when passing it to a
function therefore qualifies the language as supporting 'pass by
reference', then I think that you are confused. What you really want
to say is 'pass a reference'.


yes - you "pass a reference" _by which reference_ you are thus passing
the object whose address is taken. thus "pass by [that] reference". the
'reference' or 'pointer' is something you are _using_ as a mechanism to
pass something, which is why the word "by" is used. The only difference
is whether you, the programmer, are doing it, vs the compiler doing it.
I know this is an international forum so English may not be your
native language but do you understand the difference?


I think _you_ are the one who is not looking at the actual meanings of
the words, and unjustifiably seeing the phrase "pass by reference" as
indivisible.


Technical terms often have meanings that are not quite the same as
a naive reading would imply. Witness, for example, "call by value".
I'd be quite happy to believe that "pass by reference" was a technical
term that meant something more specific than "a reference was passed",
just as I know that "call by value" doesn't /mean/ "a value was called",
even when in the construct a value /was/ called.

--
Chris "believes seventeen improbable things before coffee" Dollin
But now the machine works, and it's /after/ coffee ..............
Jan 10 '06 #161
Joseph Dionne <sp******@minds pring.com> wrote:
It astounds me to read some the post here, most being "off topic" or "don't do
that" for people seeking solutions to problems the responders have most likely
implemented.

It also astounds me to realize how many c programmers, a low level language,
have little to no understanding of how the c compiler works, some even
claiming the OS "jumps to main" which is completely false.


Then again, it astounds me how few Unix and/or Windows weenies refer to
"the" way "the" C compiler works, as if their pet systems were the one
and only measure of computer architecture.

Richard
Jan 10 '06 #162
Chris Dollin <ke**@hpl.hp.co m> writes:
[...]
Technical terms often have meanings that are not quite the same as
a naive reading would imply. Witness, for example, "call by value".
I'd be quite happy to believe that "pass by reference" was a technical
term that meant something more specific than "a reference was passed",
just as I know that "call by value" doesn't /mean/ "a value was called",
even when in the construct a value /was/ called.


Even in plain English, I wouldn't expect "call by value" to mean that
a value is called. The phrase means that something unspecified is
called. The "by value" could mean either that the value does the
calling, or that the value is used in the process of calling.

It's true that technical phrases don't necessarily have exactly the
meaning you'd expect from the literal meanings of their constituent
words, but most of them are fairly close. Usually the technical
definition of a phrase is consistent with the plain meaning, but with
some restrictions.

--
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.
Jan 10 '06 #163

In article <ln************ @nuthaus.mib.or g>, Keith Thompson <ks***@mib.or g> writes:
mw*****@newsguy .com (Michael Wojcik) writes:

I agree with Chris (or what I take to be the main point of one of his
posts in this thread): "pass by reference" is more usefully defined
specifically as a syntactic feature of a language. And C does not
have that syntactic feature.
Here are a couple of questions for those of you who insist that the
term "pass by reference" should apply only to a built-in language
feature:

What do you call the corresponding programming technique?


"Passing a reference". I realize this may cause confusion with a
certain C++ feature; too bad. I can't change how C++ decided to
name its features. I don't go out of my way to avoid the word
"template" when discussing C either, even though it names a feature
in C++.

Since references can be implemented using mechanisms other than
pointers, a general term for the technique shouldn't mention
pointers.

The phrase "passing a reference" describes the technique in question
just as precisely as possible, and no more. The recipient gets some
token that it can use to identify the variable to be modified.
If some other language, say C+++ (sic), had built-in support for
linked lists, would you insist on not using the term "linked list" in
the context of a C program?


Why in the world would I? Lisp has built-in support for linked
lists, and that doesn't prevent me from using the term. My
objection to applying "pass-by-reference" to C has nothing to do
with its presence in other languages (except insofar as that
presence has led to the use of the term in the first place).

"Pass-by-reference" (and "call-by-reference") is a term of art of
long standing, and it historically has usually referred to a
mechanism for passing a reference which is implemented in the
syntax of the language. As I wrote in my previous post, I think
it's more useful to preserve both of those attributes in its
definition than it is to drop the latter one. Doing so preserves
an important and useful distinction, as Richard and others have
argued in this thread.

--
Michael Wojcik mi************@ microfocus.com

Push up the bottom with your finger, it will puffy and makes stand up.
-- instructions for "swan" from an origami kit
Jan 10 '06 #164
`But "glory" doesn't mean "a nice knock-down argument",' Alice objected.

`When *I* use a word,' Humpty Dumpty said, in a rather scornful tone,
`it means just what I choose it to mean -- neither more nor less.'

`The question is,' said Alice, `whether you *can* make words mean so
many different things.'

`The question is,' said Humpty, `which is to be master -- that's all.'

(see <http://www.sabian.org/Alice/lgchap06.htm>).
Chris Torek wrote:
... C remains pass-by-value. The gimmick is that the "value" of
an array is a pointer to the array's first element. In:

void f(void) {
char buf[100];
char *p;

p = buf;

we attempt to copy the "value" of buf -- an array -- to the pointer
variable p. The "value" of the array is a pointer to the array's
first element, so this sets p to point to &buf[0]. ... [Passing "buf" to a function g() likewise provides the value &buf[0].] Within g(), as for any simulation of by-reference in C, we have to
use the unary "*" operator in order to write to buf[0]:

void g(char * ptr) {
* ptr = 42;
...
}

and if we fail to prefix "ptr" with the unary "*" operator when
assigning, we will "re-bind" it so that it no longer points to
"buf" at all ...

In article <o9************ *****@newsread3 .news.atl.earth link.net>
Joseph Dionne <jd*****@hotmai l.com> wrote:Look who is being humorous. Sir, in you example, "buf" will never
change is memory value, even *if* you pass it by reference, "& buf".
[I assume "is memory value" is a typo for "its memory value".]

First, I must continue to insist that passing "&buf" does not pass
buf by-reference, as the term "by-reference" is used in compiler
circles. It passes the value &buf by value, which is what one
would expect, since C passes all parameter by value. Note that
the type of &buf differs from the type of "the value of buf" --
&buf has type (char (*)[100]), as one can see from the following:

% cat t.c
void f(void) {
char buf[100];
char *p1;
char (*p2)[50];
char (*p3)[100];

p1 = &buf; /* line 7 - draws a diagnostic */
p2 = &buf; /* line 8 - draws a diagnostic */
p3 = &buf; /* line 9 - no diagnostic */
}
% strictcc -O -c t.c
t.c: In function `f':
t.c:7: error: assignment from incompatible pointer type
t.c:8: error: assignment from incompatible pointer type
%

Second -- but perhaps even more important -- in a very real sense
(but not in the quirky C language, where the "value" of an array
is a pointer to the array's first element), the "memory value" of
buf is a sequence of 100 "char"s. Thus, whether in f() or in g(),
if we change any of the 100 array elements, we have in fact changed
the "memory value" of buf. What you mean to say is that we cannot
change the *address* of buf -- neither "buf as a whole" (i.e., we
cannot move the array from addresses A through A+99 on the x86
stack on an actual implementation, to some new set of addresses B
through B+99), nor any element of it. This is of course true.
However, the address, wherever it may be, is not in fact fixed
forever, but only for the lifetime of the given function activation:

% cat t.c
#include <stdio.h>

void f(int r) {
char buf[100];

printf("&buf[0]: %p\n", (void *)&buf[0]);
if (r > 0)
f(r - 1);
}

void g(void) {
char x[20];
f(0);
}

int main(void) {
f(1);
g();
return 0;
}
% strictcc -o t t.c
% ./t
&buf[0]: 0x8047a58
&buf[0]: 0x80479c8
&buf[0]: 0x8047a18
%

Note that three different numbers appeared. On this particular
(x86) implementation, these are addresses on the system-supplied
stack, printed as if via %#x. The system uses linear, byte-addressed
virtual memory, so these are the actual "hardware addresses"
(virtualized, of course) within the process running the program.
In the second, recursive call to f(), there are of course two
"buf"s outstanding in memory, one for each activation; in the third,
there is only one "buf" but its address is different from either
of the previous two because g()'s activation record is occupying
space above it (the x86 stack having a "natural" downward-growing
direction).
I think we all can agree the pascal and c++ support pass by
reference by different syntax. I assert the c uses yet another
syntax to implement pass by reference, nothing more or less.


Unfortunately for you and/or anyone with whom you are trying to
communicate, your definition of what constitutes "pass by reference"
disagrees with the majority in computing science / informatics.
For the rest of us, if special syntax is required on *every*
(de)reference, what we have is not an actual, language-provided,
by-reference mechanism. It is fine to say that C lets us simulate
by-reference via pointers, and when speaking informally, calling
it "by reference" is not completely out of the question (though I
myself would try to stick to the phrase "passing *a* reference")
-- but one should make it clear, if asked, that this is not what
is, in informatics, called "by-reference".

It is also worth pointing out that the distinction does show
through if the function you call, to which you pass a reference,
happens to implement the call as value-result internally and
uses a global variable and you pass the address of that global.
(See my earlier example, elsewhere in this thread.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Jan 11 '06 #165

In article <sl************ **********@rand om.yi.org>, Jordan Abel <ra*******@gmai l.com> writes:

I think _you_ are the one who is not looking at the actual meanings of
the words, and unjustifiably seeing the phrase "pass by reference" as
indivisible.


If we're going to quibble over semantics, could we at least try to
formulate decent arguments? There's ample justification for treating
the phrase "pass by reference" as a term of art.

--
Michael Wojcik mi************@ microfocus.com

Bohemia is only a stage in a man's life, except in the case of fools and
a very few others. It is not a profession. -- Arthur Ransome
Jan 12 '06 #166

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

Similar topics

699
34262
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
3462
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
2482
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
7718
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
1477
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
2671
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
1878
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
9680
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
10455
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
10228
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...
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...
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
5441
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
4116
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
3731
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2925
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.