473,404 Members | 2,137 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,404 software developers and data experts.

Question to malloc

Hi,
I would like to create a file index like updatedb on Linux does as a
part of my program, but I dont know how long the filenames could be.
Therefore I want to use malloc to keep the size of the filenames
flexible. I would expect an segmentation fault with the following
sourcecode, when invoking strcat or sprintf to assign the first value to
szFile because of missing space.
function with recursion...
char *szFile = NULL,
....
while((ptrDirentry = readdir(ptrDir)) != NULL) {

if (strcmp((*ptrDirentry).d_name, ".") != 0 &&
strcmp((*ptrDirentry).d_name, "..") != 0) {

setAbsoluteFilename(szFile, szDir, (*ptrDirentry).d_name);
....
void setAbsoluteFilename(char *szFile, char *szDir, char *szFilename) {
int iLenF = strlen(szFilename),
iLenD = strlen(szDir);

szFile = (char *)malloc(1); //???
//szFile = (char *)malloc((iLenD + iLenF + 1));

strcat(szFile, szDir);
strcat(szFile, "/");
strcat(szFile, szFilename);

//sprintf(szFile, "%s/%s", szDir, szFilename);

printf("Filename: %s, Size: %d\n", szFile, strlen(szFile));

}

Why is it possible to assign strings to szFile bigger than space is
allocated?

Regards,
T h o m a s B
Feb 20 '06 #1
13 1455
Thomas Barth wrote:
Hi,
I would like to create a file index like updatedb on Linux does as a
part of my program, but I dont know how long the filenames could be.
Therefore I want to use malloc to keep the size of the filenames
flexible. I would expect an segmentation fault with the following
sourcecode, when invoking strcat or sprintf to assign the first value to
szFile because of missing space.

char *szFile = NULL,
...
szFile = (char *)malloc(1); //???
//szFile = (char *)malloc((iLenD + iLenF + 1));

strcat(szFile, szDir);
strcat(szFile, "/");
strcat(szFile, szFilename);

Why is it possible to assign strings to szFile bigger than space is
allocated?


Because undefined behavior is "undefined." There is
no guarantee that U.B. will cause a crash or other obvious
error. It may cause a subtle error that won't be found
until the most embarrassing moment possible. There's even
a chance that U.B. will turn out to be what you wanted --
not something to bank on, obviously ...

--
Eric Sosman
es*****@acm-dot-org.invalid
Feb 20 '06 #2
Thomas Barth wrote:
Hi,
I would like to create a file index like updatedb on Linux does as a
part of my program, but I dont know how long the filenames could be.
Therefore I want to use malloc to keep the size of the filenames
flexible. I would expect an segmentation fault with the following
sourcecode, when invoking strcat or sprintf to assign the first value
to szFile because of missing space.
function with recursion...
char *szFile = NULL,
...
while((ptrDirentry = readdir(ptrDir)) != NULL) {

if (strcmp((*ptrDirentry).d_name, ".") != 0 &&
strcmp((*ptrDirentry).d_name, "..") != 0) {

setAbsoluteFilename(szFile, szDir, (*ptrDirentry).d_name);
...
void setAbsoluteFilename(char *szFile, char *szDir, char *szFilename)
{ int iLenF = strlen(szFilename),
iLenD = strlen(szDir);

szFile = (char *)malloc(1); //???
//szFile = (char *)malloc((iLenD + iLenF + 1));

strcat(szFile, szDir);
strcat(szFile, "/");
strcat(szFile, szFilename);

//sprintf(szFile, "%s/%s", szDir, szFilename);

printf("Filename: %s, Size: %d\n", szFile, strlen(szFile));

}
Why is it possible to assign strings to szFile bigger than space is
allocated?

Because C assumes you know what you're doing, and makes no assumption as to
the storage that szFile points to - you might own that memory through some
devious route ... e.g., perhaps you rewrote malloc(), and know what's after
szFile[0]!
--
==============
Not a pedant
==============
Feb 20 '06 #3
Thomas Barth wrote:

Hi,
I would like to create a file index like updatedb on Linux does as a
part of my program, but I dont know how long the filenames could be.
Therefore I want to use malloc to keep the size of the filenames
flexible. I would expect an segmentation fault with the following
sourcecode, when invoking strcat or sprintf to assign the first value to
szFile because of missing space.

function with recursion...
char *szFile = NULL,
...
while((ptrDirentry = readdir(ptrDir)) != NULL) {

if (strcmp((*ptrDirentry).d_name, ".") != 0 &&
strcmp((*ptrDirentry).d_name, "..") != 0) {

setAbsoluteFilename(szFile, szDir, (*ptrDirentry).d_name);
...

void setAbsoluteFilename(char *szFile, char *szDir, char *szFilename) {
int iLenF = strlen(szFilename),
iLenD = strlen(szDir);

szFile = (char *)malloc(1); //???
//szFile = (char *)malloc((iLenD + iLenF + 1));

strcat(szFile, szDir);
strcat(szFile, "/");
strcat(szFile, szFilename);

//sprintf(szFile, "%s/%s", szDir, szFilename);

printf("Filename: %s, Size: %d\n", szFile, strlen(szFile));

}


/* BEGIN Absolute.c output */

Filename: MyDirectory/MyFile
Length: 18

/* END Absolute.c output */
/* BEGIN Absolute.c */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char *setAbsoluteFilename(char *szDir, char *szFilename);

int main(void)
{
char *szFile;

puts("\n/* BEGIN Absolute.c output */\n");
szFile = setAbsoluteFilename("MyDirectory", "MyFile");
if (szFile != NULL) {
printf("Filename: %s\nLength: %d\n", szFile, strlen(szFile));
free(szFile);
} else {
puts("szFile == NULL");
}
puts("\n/* END Absolute.c output */");
return 0;
}

char *setAbsoluteFilename(char *szDir, char *szFilename)
{
size_t iLenF;
size_t iLenD;
char *szFile;

iLenF = strlen(szFilename);
iLenD = strlen(szDir);
szFile = malloc(iLenD + 1 + iLenF + 1);
if (szFile != NULL) {
sprintf(szFile, "%s/%s", szDir, szFilename);
}
return szFile;
}

/* END Absolute.c */
--
pete
Feb 20 '06 #4
On 2006-02-20, Thomas Barth <tx*****@web.de> wrote:
Hi,
I would like to create a file index like updatedb on Linux does as a
part of my program, but I dont know how long the filenames could be.
Therefore I want to use malloc to keep the size of the filenames
flexible. I would expect an segmentation fault with the following
sourcecode, when invoking strcat or sprintf to assign the first value to
szFile because of missing space.
function with recursion...
char *szFile = NULL,
...
while((ptrDirentry = readdir(ptrDir)) != NULL) {

if (strcmp((*ptrDirentry).d_name, ".") != 0 &&
strcmp((*ptrDirentry).d_name, "..") != 0) {

setAbsoluteFilename(szFile, szDir, (*ptrDirentry).d_name);
...
void setAbsoluteFilename(char *szFile, char *szDir, char *szFilename) {
int iLenF = strlen(szFilename),
iLenD = strlen(szDir);

szFile = (char *)malloc(1); //???
//szFile = (char *)malloc((iLenD + iLenF + 1));

strcat(szFile, szDir);
strcat(szFile, "/");
strcat(szFile, szFilename);

//sprintf(szFile, "%s/%s", szDir, szFilename);

printf("Filename: %s, Size: %d\n", szFile, strlen(szFile));

}

Why is it possible to assign strings to szFile bigger than space is
allocated?

Regards,
T h o m a s B


One of the things to keep in mind that HW Segmentation doesnt run to
that level. You basically have a big block of memory. C assumes you
take care of certain things like buffer over runs : it is one of the
reasons it is so efficient : you need to keep tabs of this yourself.

Use the memory inspection utiltiy of your debugger and you will almost
certainly see other variables being overwritten. its worth the time to
investigate as you will become far more confident in using pointers
and blocks of memory.
--
Remove evomer to reply
Feb 20 '06 #5
Thomas Barth wrote:
Hi,
I would like to create a file index like updatedb on Linux does as a
part of my program, but I dont know how long the filenames could be.
Therefore I want to use malloc to keep the size of the filenames
flexible. I would expect an segmentation fault with the following
sourcecode, when invoking strcat or sprintf to assign the first value
to szFile because of missing space.


It may sound like a tautology, but there is no defined behavior for
Undefined Behavior. So you can NOT have any expectations.

Don't do it.

Brian
Feb 20 '06 #6
"Richard G. Riley" <rg***********@gmail.com> writes:
On 2006-02-20, Thomas Barth <tx*****@web.de> wrote:
I would like to create a file index like updatedb on Linux does as a
part of my program, but I dont know how long the filenames could be.
Therefore I want to use malloc to keep the size of the filenames
flexible. I would expect an segmentation fault with the following
sourcecode, when invoking strcat or sprintf to assign the first value to
szFile because of missing space. [snip] Why is it possible to assign strings to szFile bigger than space is
allocated?


One of the things to keep in mind that HW Segmentation doesnt run to
that level. You basically have a big block of memory. C assumes you
take care of certain things like buffer over runs : it is one of the
reasons it is so efficient : you need to keep tabs of this yourself.


HW segmentation doesn't *necessarily* run to that level. Given
sufficient hardware and compiler support, an implementation could
allocate each individual object (malloc()ed block or declared object)
in its own memory segment, and trap any attempts to access memory
beyond the bounds of the intended object.

Few, if any, real-world implementations do this, but you shouldn't
make assumptions either way. A segmentation fault almost certainly
implies that you've invoked undefined behavior (though not necessarily
at the point where the fault occurs), but the reverse implication
doesn't hold.

The point is that "undefined behavior" is probably even more undefined
than you think it is, even if you take this rule into account.

--
Keith Thompson (The_Other_Keith) 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.
Feb 20 '06 #7
On Mon, 20 Feb 2006 16:36:51 +0100, Thomas Barth <tx*****@web.de>
wrote in comp.lang.c:
Hi,
I would like to create a file index like updatedb on Linux does as a
part of my program, but I dont know how long the filenames could be.
Therefore I want to use malloc to keep the size of the filenames
flexible. I would expect an segmentation fault with the following
sourcecode, when invoking strcat or sprintf to assign the first value to
szFile because of missing space.
function with recursion...
char *szFile = NULL,
...
while((ptrDirentry = readdir(ptrDir)) != NULL) {


[snip]

Never mind that, there is a far more important question here. Namely,
why are you writing outdated, discredited, Microsoft Hungarian
notation crap on Linux?

Note that even Microsoft has given up on it.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Feb 21 '06 #8
Thomas Barth wrote:

I would like to create a file index like updatedb on Linux does
as a part of my program, but I dont know how long the filenames
could be. Therefore I want to use malloc to keep the size of the
filenames flexible. I would expect an segmentation fault with
the following sourcecode, when invoking strcat or sprintf to
assign the first value to szFile because of missing space.
.... snip ...
From the description of stdio.h in N869:


FILENAME_MAX

which expands to an integer constant expression that is the
size needed for an array of char large enough to hold the
longest file name string that the implementation guarantees
can be opened;

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
Also see <http://www.safalra.com/special/googlegroupsreply/>

Feb 21 '06 #9
Am 02/21/2006 05:29 AM schrieb Jack Klein:

function with recursion...
char *szFile = NULL,
...
while((ptrDirentry = readdir(ptrDir)) != NULL) {
[snip]

Never mind that, there is a far more important question here. Namely,
why are you writing outdated, discredited, Microsoft Hungarian
notation crap on Linux?


I like that style. I ve seen part of the sourcecodes of Windows 2000 two
years ago. I was quite impressed. I dont care of what os I am
programming for.

Note that even Microsoft has given up on it.


How do you know that? Have you seen the sourcecodes of WindowsXP/Vista?

Btw. thanks for all your good pieces of advises!

T h o m a s B
Feb 21 '06 #10
On 2006-02-20, Keith Thompson <ks***@mib.org> wrote:
"Richard G. Riley" <rg***********@gmail.com> writes:
On 2006-02-20, Thomas Barth <tx*****@web.de> wrote:
I would like to create a file index like updatedb on Linux does as a
part of my program, but I dont know how long the filenames could be.
Therefore I want to use malloc to keep the size of the filenames
flexible. I would expect an segmentation fault with the following
sourcecode, when invoking strcat or sprintf to assign the first value to
szFile because of missing space. [snip] Why is it possible to assign strings to szFile bigger than space is
allocated?
One of the things to keep in mind that HW Segmentation doesnt run to
that level. You basically have a big block of memory. C assumes you
take care of certain things like buffer over runs : it is one of the
reasons it is so efficient : you need to keep tabs of this yourself.


HW segmentation doesn't *necessarily* run to that level. Given
sufficient hardware and compiler support, an implementation could
allocate each individual object (malloc()ed block or declared object)
in its own memory segment, and trap any attempts to access memory
beyond the bounds of the intended object.


There are many "coulds" there and nothing helpful to a newbie trying t
understand why he should be careful not to overwrite unprotected memory.

Few, if any, real-world implementations do this, but you shouldn't
make assumptions either way. A segmentation fault almost certainly
implies that you've invoked undefined behavior (though not necessarily
at the point where the fault occurs), but the reverse implication
doesn't hold.
Of course and no one said any different.

The point is that "undefined behavior" is probably even more undefined
than you think it is, even if you take this rule into account.

Possibly more undefined than you think I think :-; But again, I dont
see how this has anything to do with advising a new programmer on
being careful with pointers and memory allocations : a cornerstone of
C programming.

As you will recall the OP "expected" a seg fault : I pointed out that
that is not necessarily the case - so we seem to have come full about
for some reason.
--
Remove evomer to reply
Feb 21 '06 #11
"Richard G. Riley" <rg***********@gmail.com> writes:
On 2006-02-20, Keith Thompson <ks***@mib.org> wrote:
"Richard G. Riley" <rg***********@gmail.com> writes:
On 2006-02-20, Thomas Barth <tx*****@web.de> wrote:
I would like to create a file index like updatedb on Linux does as a
part of my program, but I dont know how long the filenames could be.
Therefore I want to use malloc to keep the size of the filenames
flexible. I would expect an segmentation fault with the following
sourcecode, when invoking strcat or sprintf to assign the first value to
szFile because of missing space. [snip]
Why is it possible to assign strings to szFile bigger than space is
allocated?

One of the things to keep in mind that HW Segmentation doesnt run to
that level. You basically have a big block of memory. C assumes you
take care of certain things like buffer over runs : it is one of the
reasons it is so efficient : you need to keep tabs of this yourself.


HW segmentation doesn't *necessarily* run to that level. Given
sufficient hardware and compiler support, an implementation could
allocate each individual object (malloc()ed block or declared object)
in its own memory segment, and trap any attempts to access memory
beyond the bounds of the intended object.


There are many "coulds" there and nothing helpful to a newbie trying t
understand why he should be careful not to overwrite unprotected memory.


It could help a newbie understand why he gets a seg fault when he runs
his program on one system, and doesn't get a seg fault when he runs it
on another system.

What you wrote could imply that a buffer overrun *won't* cause a seg
fault. My point is that it may or may not.

In any case, I wasn't necessarily talking just to the OP. This is a
public forum, after all. And even if my point went over the OP's head
(an assumption I do not make), it can't hurt to be aware that there
are details beyond what he's already learned.

[snip]
The point is that "undefined behavior" is probably even more undefined
than you think it is, even if you take this rule into account.


Possibly more undefined than you think I think :-;


It was meant as a general "you", not you personally.
But again, I dont
see how this has anything to do with advising a new programmer on
being careful with pointers and memory allocations : a cornerstone of
C programming.

As you will recall the OP "expected" a seg fault : I pointed out that
that is not necessarily the case - so we seem to have come full about
for some reason.


Your point was that one shouldn't assume anything about what happens
on a buffer overflow. I was just emphasizing that point; sometimes
you get a seg fault, sometimes you don't.

--
Keith Thompson (The_Other_Keith) 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.
Feb 21 '06 #12
On 2006-02-21, Keith Thompson <ks***@mib.org> wrote:

Your point was that one shouldn't assume anything about what happens
on a buffer overflow. I was just emphasizing that point; sometimes
you get a seg fault, sometimes you don't.


We are in agreement then :-; And thanks for the clarification to my
other post about the unsigned char - better to be 100% clear althought
I would be surprised if there were any differences in the
outcome. Hmm. Or would there?

--
Remove evomer to reply
Feb 21 '06 #13

In article <43***************@yahoo.com>, CBFalconer <cb********@yahoo.com> writes:
Thomas Barth wrote:

I would like to create a file index like updatedb on Linux does
as a part of my program, but I dont know how long the filenames
could be.


FILENAME_MAX

which expands to an integer constant expression that is the
size needed for an array of char large enough to hold the
longest file name string that the implementation guarantees
can be opened;


Unfortunately, FILENAME_MAX is not reliable, in that there are
implementations which claim conformance but provide infelicitous
values for FILENAME_MAX, and argue that these are within the letter
of the standard. See for example [1], part of a discussion about
HP-UX 11's use of 14 for FILENAME_MAX.

While not everyone will agree with the arguments made in that thread
(and note that it's Alan Balmer - who I hope we can agree knows
something about C - who's defending HP here), the practical result is
that FILENAME_MAX cannot portably be used in the manner that a
cursory reading of the standard might suggest.

I'll note that the final clause you quoted above appears to give an
implementation plenty of weasel room; an implementation need not
"guarantee" that any file of any name "can be opened".

My view, frankly, is that FILENAME_MAX is inherently broken anyway,
since there are plenty of implementations that can produce programs
for execution environments which they cannot have full knowledge of.
Compiler authors are not oracles. We're stuck with FILENAME_MAX for
compatibility, but I believe new code should avoid it.
1. http://groups.google.com/group/comp....24d5e9ae3f8a3f

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

The presence of those seeking the truth is infinitely preferable to
the presence of those who think they've found it. -- Terry Pratchett
Feb 21 '06 #14

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

Similar topics

46
by: sbayeta | last post by:
Hi, I'd like to know who is responsible of memory recycling and defragmentation in a C/C++ program, assuming all the memory allocation/deallocation is done using malloc/free or new/delete. ...
110
by: Vijay Kumar R Zanvar | last post by:
Hi, Which section of C99 says that return value of malloc(3) should not be casted? Thanks. -- Vijay Kumar R Zanvar My Home Page - http://www.geocities.com/vijoeyz/
51
by: Alan | last post by:
hi all, I want to define a constant length string, say 4 then in a function at some time, I want to set the string to a constant value, say a below is my code but it fails what is the correct...
9
by: zerro | last post by:
Hello, I try to understand heap overflows (under Linux), but can not understand one thing with freeing memory allocated with malloc(). Here it comes: I have a program called 1.c: main() {...
26
by: Method Man | last post by:
Say I have the following: int main(void) { char* p, q; p = (char*) malloc(sizeof(char)*10); q = (p + 100) - 99; /* legal? */ free(q - 1); /* legal? */ .... return 0; }
36
by: Martin Andert | last post by:
Hello, I have a question regarding malloc and free. Here my code sample: int main() { /* allocating dynamic memory for array */ int* array = (int*) malloc(5 * sizeof(int)); /* ... program...
18
by: steve | last post by:
I'm trying to create a structure of three pointers to doubles. For which I have: typedef struct { double *lst_t, *lst_vc, *lst_ic; } last_values; I then need to allocate space for...
15
by: sethukr | last post by:
Hi everybody, While running the following program in GCC, i'm very much screwed. main() { char *ptr1; char arr; int i; char *ptr2;
25
by: Why Tea | last post by:
Thanks to those who have answered my original question. I thought I understood the answer and set out to write some code to prove my understanding. The code was written without any error checking....
10
by: somenath | last post by:
Hi All, I have one question regarding return value cast of malloc. I learned that we should not cast the return value of malloc because it is bug hider. But my question is as mentioned...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...
0
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...
0
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,...

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.