473,756 Members | 1,969 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

accessing freed memory without error

Hi,

Why I am not getting any run time error while accessing a freed memory
in following code. This is printing h in std output.

#include<stdio. h>
main()
{
char* buffer = (char*)malloc(6 );
strcpy(buffer," hello");
free(buffer);
printf("buffer= %c\n", *buffer);
}

-Sachin

Nov 14 '05 #1
14 1643
<sa********@yah oo.com> wrote in message
news:11******** *************@z 14g2000cwz.goog legroups.com...
Hi,

Why I am not getting any run time error while accessing a freed memory
in following code. This is printing h in std output.

#include<stdio. h>
main()
{
char* buffer = (char*)malloc(6 );
strcpy(buffer," hello");
free(buffer);
printf("buffer= %c\n", *buffer);
}


You've entered the realm of undefined behaviour with the printf, and
anything at all (including printing h on stdout) can happen. Simply don't do
it.
Nov 14 '05 #2

<sa********@yah oo.com> wrote in message
news:11******** *************@z 14g2000cwz.goog legroups.com...
Hi,

Why I am not getting any run time error while accessing a freed memory
in following code.
C does not have any "run-time-errors". Accessing freed (i.e. non-allocated)
memory results in undefined behavior. If pink rabbits would jump out of your
computer, there would still be nothing wrong as far as the standard is
concerned.
This is printing h in std output.

#include<stdio. h>
main()
{
char* buffer = (char*)malloc(6 );
strcpy(buffer," hello");
free(buffer); printf("buffer= %c\n", *buffer);
If that would print the content of the last issue of PlayGirl, it would be
right, too. }


Checkout the FAQ.

http://www.eskimo.com/~scs/C-faq/q7.20.html
Nov 14 '05 #3

dandelion wrote:
C does not have any "run-time-errors". Accessing freed (i.e. non-allocated) memory results in undefined behavior. If pink rabbits would jump out of your computer, there would still be nothing wrong as far as the standard is concerned.
If that would print the content of the last issue of PlayGirl, it would be right, too.
}


ROTFL. Pink Rabbits (?), PlayGirl(!) issue...

Nov 14 '05 #4
<sa********@yah oo.com> wrote in message
news:11******** *************@z 14g2000cwz.goog legroups.com...
Hi,

Why I am not getting any run time error while accessing a freed memory
in following code.
Because your program's behavior is undefined. This means
that from the language perspective, it could do absolutely
anything at all, from 'seems to work', to a crash, anything
in between, or something else.
This is printing h in std output.
It also might have caused the monitor to fall of the desk.
Moral: Don't Do That.

#include<stdio. h>
#include <stdlib.h> /* declares 'malloc()' and 'free()' */
#include <string.h> /* declares 'strcpy()' */
main()
int main(void)
{
char* buffer = (char*)malloc(6 );
You forgot to check if 'malloc()' succeeded. If it
failed, it returns NULL, in which case the call
to 'strcpy()' would give undefined behavior, because
it would try to dereference a null pointer.

Also, your casting of 'malloc()'s return value hides a
serious error: There's no prototype for 'malloc()' in
scope, which will cause a C89 compiler to assume it
returns type 'int'. So your cast tries to convert
a pointer type to an integer type. The language
does not define such a conversion. This conversion
is implementation-defined, but in any case it will
very likely corrupt the returned pointer value, in
which case you have more undefined behavior.
strcpy(buffer," hello");
free(buffer);
printf("buffer= %c\n", *buffer);
return 0;
}


It's been a while since I've seen so many errors in such
a small piece of code. :-)

-Mike
Nov 14 '05 #5
sa********@yaho o.com wrote:
Hi,

Why I am not getting any run time error while accessing a freed memory
in following code.
Dumb luck. Just as using malloc() and free() without the prototypes
found in <stdlib.h> and using strcpy without the prototype <string.h>
gave you no error.
This is printing h in std output.
Not for me. A version of your program with other errors corrected
follows yours; note that the output is not what you claim.
#include<stdio. h>
main()
{
char* buffer = (char*)malloc(6 );
strcpy(buffer," hello");
free(buffer);
printf("buffer= %c\n", *buffer);
}


#include <stdio.h>
#include <stdlib.h> /* note */
#include <string.h> /* note */

int main(void)
{
char *buffer = malloc(6); /* note */
if (!buffer) {
fprintf(stderr, "malloc failed.\n");
exit(EXIT_FAILU RE);
}
strcpy(buffer, "hello");
free(buffer);
printf("buffer= %c\n", *buffer); /* impromper use of pointer */
return 0;
}

[output]
buffer=

BTW: please note the other threads on preserving indenting when using
google.com. You can follow those suggestions or -- even better -- stop
using google for posting.
Nov 14 '05 #6

"Taran" <ta************ @honeywell.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .

dandelion wrote:
C does not have any "run-time-errors". Accessing freed (i.e.

non-allocated)
memory results in undefined behavior. If pink rabbits would jump out

of your
computer, there would still be nothing wrong as far as the standard

is
concerned.
If that would print the content of the last issue of PlayGirl, it

would be
right, too.
}


ROTFL. Pink Rabbits (?), PlayGirl(!) issue...


Hey! Can't a girl have some fun, too? ;-).
Nov 14 '05 #7
On Wed, 12 Jan 2005 18:13:15 +0000, Mike Wahler wrote:
<sa********@yah oo.com> wrote in message
news:11******** *************@z 14g2000cwz.goog legroups.com...
....
int main(void)
{
char* buffer = (char*)malloc(6 );


You forgot to check if 'malloc()' succeeded. If it
failed, it returns NULL, in which case the call
to 'strcpy()' would give undefined behavior, because
it would try to dereference a null pointer.

Also, your casting of 'malloc()'s return value hides a
serious error: There's no prototype for 'malloc()' in
scope, which will cause a C89 compiler to assume it
returns type 'int'. So your cast tries to convert
a pointer type to an integer type.


Well, an int to a pointer. But that's not the problem. The code invokes
undefined behaviour because it tries to call a function with a type that
is not compatible with the function's definition. So the code has left the
rails before the cast is executed.

Lawrence
Nov 14 '05 #8

"dandelion" <da*******@mead ow.net> wrote in message
news:41******** *************@d reader10.news.x s4all.nl...

"Taran" <ta************ @honeywell.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .

dandelion wrote:
C does not have any "run-time-errors". Accessing freed (i.e.

non-allocated)
memory results in undefined behavior. If pink rabbits would jump out

of your
computer, there would still be nothing wrong as far as the standard

is
concerned.
If that would print the content of the last issue of PlayGirl, it

would be
right, too.
> }


ROTFL. Pink Rabbits (?), PlayGirl(!) issue...


Hey! Can't a girl have some fun, too? ;-).


In that case, I'd think you'd want not the 'content',
but the pictures.

"Honey, I buy 'em for the articles, honest!"

:-)

-Mike
Nov 14 '05 #9
Lawrence Kirby wrote:
On Wed, 12 Jan 2005 18:13:15 +0000, Mike Wahler wrote:
<sa********@y ahoo.com> wrote in message
news:11****** *************** @z14g2000cwz.go oglegroups.com. ..
....
int main(void)
{
char* buffer = (char*)malloc(6 );

You forgot to check if 'malloc()' succeeded. If it
failed, it returns NULL, in which case the call
to 'strcpy()' would give undefined behavior, because
it would try to dereference a null pointer.

Also, your casting of 'malloc()'s return value hides a
serious error: There's no prototype for 'malloc()' in
scope, which will cause a C89 compiler to assume it
returns type 'int'. So your cast tries to convert
a pointer type to an integer type.


Well, an int to a pointer. But that's not the problem. The code invokes

Just wondering what will happen in a 64 bit m/c? 32 bit integer may yield a
junk 64 bit pointer value. Because 64 bit return value of malloc has now
truncated to 32 bit integer.
undefined behaviour because it tries to call a function with a type that
is not compatible with the function's definition. So the code has left the
rails before the cast is executed.

Lawrence

Krishanu

Nov 14 '05 #10

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

Similar topics

73
2479
by: David Scarlett | last post by:
Is the following code safe? SomeType *a, *b; /* Some code.... */ free(a);
72
3619
by: ravi | last post by:
I have a situation where i want to free the memory pointed by a pointer, only if it is not freed already. Is there a way to know whether the memory is freed or not?
5
10469
by: Thor W Hammer | last post by:
Hello all, Is it possible to find out if a script is freed? This is actual when having a pointer to a function and should determine if it is freed so we don't call it and get error.. TWH
13
3611
by: lovecreatesbeauty | last post by:
/* How do free() know how many elements should be freed in a dynamic array? When free a single variable, the amount of byte of memory can be retrieved from the type of variable itself. Now, suppose there is an array of more than one element need to be freed, as free() doesn't accept a argument indicating the size, how can
1
2141
by: lars.uffmann | last post by:
Hello everyone! I just debugged a pretty huge project, eliminating basically every memory leak that would occur with the current configuration files, at least according to the mtrace() tool from the library <mcheck.h>. Now the very last bugs I seem to be incapable of eliminating are: - 0x000000000061f460 Free 387310 was never alloc'd 0x2aaaab053b53 - 0x000000000061f040 Free 387311 was never alloc'd 0x2aaaab053b53
10
8338
by: frakie | last post by:
Hi 'body, is there a method to check if a pointer is pointing a freed memory location?
0
9455
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
10031
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
9869
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
9838
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
8709
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
7242
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...
0
5140
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
3805
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
3354
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.