473,594 Members | 2,839 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Overwriting Allocated Memory from malloc()


I have been messing around with buffers, and
I found it peculiar that the code below will
run without a segmentation fault.

As far as I know, overwriting the allocated space
from a call to malloc() results in undefined
behavior.

Any ideas why overwriting the dynamically
assigned space doesn't cause a segmentation
fault?

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

int
main(void)
{

char *ptr = NULL;
char buffer[256]; /* intentionally did not initialize */
int y = 0;

if ( ( ptr = malloc(1) ) == 0 ) {
perror("malloc( ) problem");
exit(1);
}

for ( int i; i < 255; i++ )
buffer[i] = 'Z';

while ( (ptr[y] = buffer[y]) != '\0' )
y++;
(void)printf("p tr is: %s\n", ptr);
free(ptr);

return 0;
}
Nov 14 '05 #1
19 4489
On Thu, 08 Jul 2004 18:22:16 -0700, tweak <xb**********@c ox.net> wrote:
As far as I know, overwriting the allocated space
from a call to malloc() results in undefined
behavior.

Any ideas why overwriting the dynamically
assigned space doesn't cause a segmentation
fault?


Because undefined behavior by definition can be anything at all. You
were lucky, nothing more.

--
Eric Amick
Columbia, MD
Nov 14 '05 #2


tweak wrote:
I have been messing around with buffers, and
I found it peculiar that the code below will
run without a segmentation fault.

As far as I know, overwriting the allocated space
from a call to malloc() results in undefined
behavior.

Any ideas why overwriting the dynamically
assigned space doesn't cause a segmentation
fault?


Why would you expect undefined behavior(UB) to cause seg fault?
To me, UB seems to suggest that anything can happen; good, bad, expected

or unexpected.
Nov 14 '05 #3
On Thu, 08 Jul 2004 18:22:16 -0700, tweak <xb**********@c ox.net>
wrote:

I have been messing around with buffers, and
I found it peculiar that the code below will
run without a segmentation fault.

As far as I know, overwriting the allocated space
from a call to malloc() results in undefined
behavior.

Any ideas why overwriting the dynamically
assigned space doesn't cause a segmentation
fault?
Undefined behavior is not guaranteed to cause a segment fault. In its
most pernicious form, it appears to work properly until it can satisfy
one of Murphy's laws.

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

int
main(void)
{

char *ptr = NULL;
char buffer[256]; /* intentionally did not initialize */
int y = 0;

if ( ( ptr = malloc(1) ) == 0 ) {
perror("malloc( ) problem");
exit(1);
}

for ( int i; i < 255; i++ )
buffer[i] = 'Z';

while ( (ptr[y] = buffer[y]) != '\0' )
y++;
(void)printf("p tr is: %s\n", ptr);
free(ptr);

return 0;
}


<<Remove the del for email>>
Nov 14 '05 #4
Barry Schwarz wrote:
On Thu, 08 Jul 2004 18:22:16 -0700, tweak <xb**********@c ox.net>
wrote:

I have been messing around with buffers, and
I found it peculiar that the code below will
run without a segmentation fault.

As far as I know, overwriting the allocated space

from a call to malloc() results in undefined

behavior.

Any ideas why overwriting the dynamically
assigned space doesn't cause a segmentation
fault?

Undefined behavior is not guaranteed to cause a segment fault. In its
most pernicious form, it appears to work properly until it can satisfy
one of Murphy's laws.


I tried different sizes of the buffer array, and I was able to generate
a segmentation fault. Since the compiler tells me everything is okay,
and since the software appears to work, are there any audit tools to
check for problems like this one, where the compiler doesn't warn of
a potential problem (beyond just the malloc() ones listed in the FAQ)?

I'm sure you grep or use an equivalent tool in the many different
OS's we have. But are there any portable tools?

Of course, writing ISO C99 code that is portable is preferred, but you
can miss stuff as the number of lines of code and number of files increase.

Brian
Nov 14 '05 #5

"tweak" <xb**********@c ox.net> wrote in message news:PJpHc.787$ rr.721@fed1read 02...
Barry Schwarz wrote:
On Thu, 08 Jul 2004 18:22:16 -0700, tweak <xb**********@c ox.net>
wrote:
[..] I tried different sizes of the buffer array, and I was able to generate
a segmentation fault. Since the compiler tells me everything is okay,
and since the software appears to work, are there any audit tools to
check for problems like this one, where the compiler doesn't warn of
a potential problem (beyond just the malloc() ones listed in the FAQ)?

lint may be helpful. See below.
I'm sure you grep or use an equivalent tool in the many different
OS's we have. But are there any portable tools?

Of course, writing ISO C99 code that is portable is preferred, but you
can miss stuff as the number of lines of code and number of files increase.

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

int
main(void)
{

char *ptr = NULL;
char buffer[256]; /* intentionally did not initialize */
int y = 0;

if ( ( ptr = malloc(1) ) == 0 ) {
perror("malloc( ) problem");
exit(1);
}

for ( int i; i < 255; i++ )
i is uninitialized. UB.
buffer[i] = 'Z';

while ( (ptr[y] = buffer[y]) != '\0' )
y++;
(void)printf("p tr is: %s\n", ptr);
free(ptr);

return 0;
}


F:\>splint overflow.c
Splint 3.0.1.6 --- 11 Feb 2002

overflow2.c: (in function main)
overflow2.c(15, 18): Unrecognized identifier: NULL
Identifier used in code has not been declared. (Use -unrecog to inhibit
warning)
overflow2.c(19, 19): Unrecognized identifier: malloc
overflow2.c(20, 10): Unrecognized identifier: perror
overflow2.c(21, 10): Unrecognized identifier: exit
overflow2.c(27, 15): Index of possibly null pointer ptr: ptr
A possibly null pointer is dereferenced. Value is either the result of a
function which may return null (in which case, code should check it is not
null), or a global, parameter or structure field declared with the null
qualifier. (Use -nullderef to inhibit warning)
overflow2.c(19, 19): Storage ptr may become null
overflow2.c(27, 24): Value buffer[] used before definition
An rvalue is used that may not be initialized to a value on some execution
path. (Use -usedef to inhibit warning)
overflow2.c(29, 12): Unrecognized identifier: printf
overflow2.c(30, 6): Unrecognized identifier: free

Finished checking --- 8 code warnings
Nov 14 '05 #6
Vijay Kumar R Zanvar wrote:
"tweak" <xb**********@c ox.net> wrote in message news:PJpHc.787$ rr.721@fed1read 02...
Barry Schwarz wrote:
On Thu, 08 Jul 2004 18:22:16 -0700, tweak <xb**********@c ox.net>
wrote:

[..]
I tried different sizes of the buffer array, and I was able to generate
a segmentation fault. Since the compiler tells me everything is okay,
and since the software appears to work, are there any audit tools to
check for problems like this one, where the compiler doesn't warn of
a potential problem (beyond just the malloc() ones listed in the FAQ)?

lint may be helpful. See below.


Thanks. I used google to find it. I will start using it tomorrow.
I also found a splint. I will look at them both when I have more
energy.


I'm sure you grep or use an equivalent tool in the many different
OS's we have. But are there any portable tools?

Of course, writing ISO C99 code that is portable is preferred, but you
can miss stuff as the number of lines of code and number of files increase.

Brian

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

int
main(void)
{

char *ptr = NULL;
char buffer[256]; /* intentionally did not initialize */
int y = 0;

if ( ( ptr = malloc(1) ) == 0 ) {
perror("malloc( ) problem");
exit(1);
}

for ( int i; i < 255; i++ )

i is uninitialized. UB.


Good catch. My source code reads as : for (int i = 0; i < 255; i++).
I made a typo.

Also since malloc() returns a NULL pointer on failure, the line that
starts with if should read:

if ( ( ptr = malloc(1) ) == NULL ) {

to be consistent even though it's just a style thing.

Thanks,

Brian
Nov 14 '05 #7
tweak <xb**********@c ox.net> wrote:
"tweak" <xb**********@c ox.net> wrote in message news:PJpHc.787$ rr.721@fed1read 02...
if ( ( ptr = malloc(1) ) == 0 ) {
Also since malloc() returns a NULL pointer on failure,
No, it doesn't. It returns a null pointer. NULL is a macro, which
expands to a null pointer _constant_, and exists only in your source
code; a null pointer is an object, which exists during runtime.
the line that starts with if should read:

if ( ( ptr = malloc(1) ) == NULL ) {

to be consistent even though it's just a style thing.


There's nothing consistent about it. The original is just as good, just
as clear, and just as proper C. The only way in which this version could
be more, rather than just as, consistent, is if you've used NULL
everywhere else in your code; but that is consistency with _yourself_,
not with C. C does not distinguish between those two versions; both must
work equally well.

Richard
Nov 14 '05 #8
In 'comp.lang.c', Eric Amick <er********@com cast.net> wrote:
On Thu, 08 Jul 2004 18:22:16 -0700, tweak <xb**********@c ox.net> wrote:
As far as I know, overwriting the allocated space
from a call to malloc() results in undefined
behavior.

Any ideas why overwriting the dynamically
assigned space doesn't cause a segmentation
fault?


Because undefined behavior by definition can be anything at all. You
were lucky, nothing more.


I'd rather have said "you were unlucky".

--
-ed- get my email here: http://marreduspam.com/ad672570
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-reference: http://www.dinkumware.com/manuals/reader.aspx?lib=c99
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 14 '05 #9
In 'comp.lang.c', tweak <xb**********@c ox.net> wrote:
I have been messing around with buffers, and
I found it peculiar that the code below will
run without a segmentation fault.
May be it's correct, who knows ?
As far as I know, overwriting the allocated space
from a call to malloc() results in undefined
behavior.
Yes.
Any ideas why overwriting the dynamically
assigned space doesn't cause a segmentation
fault?
Why should do it ? An undefined behaviour in unpredictable. Anything may
happen, including a safe behaviour. Imagine you ask for 50 char. Some
implementation could give you the address of a 64 char block. You could write
at [50] to [63] safely.

The problem is that you don't know about the actual safe size. The C-language
only guarantees that the wanted size is safe. I know other implementations of
memory allocator (PSoS) where an additional parameter is used to return the
actual allocated size.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

int
main(void)
{

char *ptr = NULL;
char buffer[256]; /* intentionally did not initialize */
int y = 0;

if ( ( ptr = malloc(1) ) == 0 ) {
Should be '== NULL' to preserve reader's mental health.
perror("malloc( ) problem");
exit(1);
exit (EXIT_FAILURE);

for portability.
}

for ( int i; i < 255; i++ )
Warning, This construct only works in C99.
buffer[i] = 'Z';

while ( (ptr[y] = buffer[y]) != '\0' )
Of course, you are overwriting the array pointed by ptr, but you know it
already.
y++;
Because 'buffer' was intentionally not initialized, there is no guarantee
that a 0 is present at [255].
(void)printf("p tr is: %s\n", ptr);
Can be anything.
free(ptr);

return 0;
}

--
-ed- get my email here: http://marreduspam.com/ad672570
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-reference: http://www.dinkumware.com/manuals/reader.aspx?lib=c99
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 14 '05 #10

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

Similar topics

4
3849
by: Thomas Paul Diffenbach | last post by:
Can anyone point me to an open source library of /statically allocated/ data structures? I'm writing some code that would benefit from trees, preferably self balancing, but on an embedded system that doesn't offer dynamic memory allocation (to be clear: no malloc, no realloc), and with rather tight memory constraints. Writing my own malloc to do dynamic allocation from some static pool isn't really an option, for various reasons, not...
3
2573
by: Hassan Iqbal | last post by:
Hi, (1)if i do the memory allocation like: int **p; p= malloc(n*sizeof p); for(i=0;i<n;i++) /* i and n are integers */ p= malloc(n*sizeof p); then in that case is this command sufficient to free all the allocated memory:
11
2291
by: binaya | last post by:
Dear all, Say I allocate a block of memory using the command malloc.I have a question. Can I deallocate certain portion of it only during runtime ? For eg: Say I allocate 5 pointers to int as below.
31
3698
by: bilbothebagginsbab5 AT freenet DOT de | last post by:
Hello, hello. So. I've read what I could find on google(groups) for this, also the faq of comp.lang.c. But still I do not understand why there is not standard method to "(...) query the malloc package to find out how big an allocated block is". ( Question 7.27) Is there somwhere explained why - because it would seem to me, that free()
29
4381
by: keredil | last post by:
Hi, Will the memory allocated by malloc get released when program exits? I guess it will since when the program exits, the OS will free all the memory (global, stack, heap) used by this process. Is it correct?
6
2308
by: lovecreatesbeauty | last post by:
Hello experts, 1. Does C guarantee the data layout of the memory allocated by malloc function on the heap. I mean, for example, if I allocate a array of 100 elements of structure, can I always reference a correct/valid structure member upon that allocated memory? If I allocate memory, for example like this way:
5
5588
by: nmtoan | last post by:
Hi, I could not find any answer to this simple question of mine. Suppose I have to write a program, the main parts of it are as follows: #include <blahblah.h> struct {
19
2348
by: pinkfloydhomer | last post by:
Please read the example below. I'm sorry I couldn't make it smaller, but it is pretty simple. When client code is calling newThingy(), it is similar to malloc: the client gets a pointer to a chunk of memory that it can use for it's own purposes. But on the "library" side, I want to be able to do some book-keeping for each memory block that I hand out. I want some "hidden" meta-data (that I keep in struct Container) to be associated...
74
4634
by: ballpointpenthief | last post by:
If I have malloc()'ed a pointer and want to read from it as if it were an array, I need to know that I won't be reading past the last index. If this is a pointer to a pointer, a common technique seems to be setting a NULL pointer to the end of the list, and here we know that the allocated memory has been exhausted. All good. When this is a pointer to another type, say int, I could have a variable that records how much memory is being...
0
7946
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...
1
8009
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
6661
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
5411
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
3867
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
3903
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2389
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
1
1482
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1216
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.