473,811 Members | 2,597 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Memory allocation problem

Hello,

I noticed that when I dynamically create an array of chars, the
resulting size of the allocated memory block is larger by about 15
bytes than what I specified. Here is example code:

char *createTextBuff er(char *buffer, int length)
{
buffer = new char[length];

if (buffer == NULL) {
return NULL;
}
length = strlen(buffer); // Current buffer shows larger size.
return buffer;
}

The above program causes a crash when destroying the allocated memory
via delete. I suspect the crash problem originates at the time of
allocation (i.e., possible memory corruption at time of allocation).

I am using MS Developer Studio 6.0 (SP 6) on AMD Athlon. I get the same
results on a Pentium 4. Any suggestions or comments on what I am doing
in the code is much appreciated.

TIA
Alabi

Dec 17 '05 #1
10 4426
AlabiChin napisa³:
Hello,

I noticed that when I dynamically create an array of chars, the
resulting size of the allocated memory block is larger by about 15
bytes than what I specified. Here is example code:

char *createTextBuff er(char *buffer, int length)
{
buffer = new char[length];

if (buffer == NULL) {
return NULL;
// new does not return NULL on error, it throws
// so this check is meaningless
}
length = strlen(buffer); // Current buffer shows larger size.
return buffer;
}

The above program causes a crash when destroying the allocated memory
via delete.
That's because you should destroy it using 'delete[]',
not 'delete'.
I suspect the crash problem originates at the time of
allocation (i.e., possible memory corruption at time of allocation).
I don't think so.

I am using MS Developer Studio 6.0 (SP 6) on AMD Athlon. I get the same
results on a Pentium 4. Any suggestions or comments on what I am doing
in the code is much appreciated.


Notice that you don't clear the allocated buffer, therefore
it contains garbage. The function strlen() looks for the
first occurrence of the '\0' terminator, which luckily
falls 'about 15 bytes' after the end of your buffer.

HTH,
- J.
Dec 17 '05 #2
AlabiChin wrote:
Hello,

I noticed that when I dynamically create an array of chars, the
resulting size of the allocated memory block is larger by about 15
bytes than what I specified. Here is example code:

char *createTextBuff er(char *buffer, int length)
{
buffer = new char[length];

if (buffer == NULL) {
This check is unnecessary. new either returns a valid pointer or (if no
memory is available) throws an exception. It never returns a null pointer.
return NULL;
}
length = strlen(buffer); // Current buffer shows larger size.
return buffer;
}
strlen expects a C style string, i.e. a null terminated character array. You
gave it uninitialized memory, which means the behavior is undefined.
The above program causes a crash when destroying the allocated memory
via delete. I suspect the crash problem originates at the time of
allocation (i.e., possible memory corruption at time of allocation).


No, it originates at the time you used strlen on it. Probably, strlen went
past the end of the array to find the null character.

Dec 17 '05 #3
AlabiChin wrote:
Hello,

I noticed that when I dynamically create an array of chars, the
resulting size of the allocated memory block is larger by about 15
bytes than what I specified. Here is example code:

char *createTextBuff er(char *buffer, int length)
{
buffer = new char[length];

if (buffer == NULL) {
return NULL;
}
length = strlen(buffer); // Current buffer shows larger size.
return buffer;
}

The above program causes a crash when destroying the allocated memory
via delete. I suspect the crash problem originates at the time of
allocation (i.e., possible memory corruption at time of allocation).

I am using MS Developer Studio 6.0 (SP 6) on AMD Athlon. I get the same
results on a Pentium 4. Any suggestions or comments on what I am doing
in the code is much appreciated.

TIA
Alabi


You have an uninitialized buffer. Calling strlen with such a buffer is
likely to cause a crash right then and there. strlen does not return
the length of the buffer, it returns the length of a nul-terminated
string that has been stored in the buffer. But you do not have such a
string in the buffer.

--
Scott McPhillips [VC++ MVP]

Dec 17 '05 #4
AlabiChin wrote:
I noticed that when I dynamically create an array of chars, the
resulting size of the allocated memory block is larger by about 15
bytes than what I specified.
whilst "new" can be expected to allocate a few more bytes than
requested
(housekeeping) 15 bytes sounds like a lot.

Here is example code:

char *createTextBuff er(char *buffer, int length)
{
buffer = new char[length];

if (buffer == NULL) {
return NULL;
}
length = strlen(buffer); // Current buffer shows larger size.
you can't do strlen on a newly allocated chunk of memory. How do you
know
"new" returns a nul terminated string?
return buffer;
}

The above program causes a crash when destroying the allocated memory
via delete.
what does your delete look like?

I suspect the crash problem originates at the time of
allocation (i.e., possible memory corruption at time of allocation).
I suspect there's something else wrong with your program. Standard
libraries
can have bugs, but always suspect your own (newly written) code first
I am using MS Developer Studio 6.0 (SP 6) on AMD Athlon. I get the same
results on a Pentium 4. Any suggestions or comments on what I am doing
in the code is much appreciated.

--
Nick Keighley

Dec 17 '05 #5
AlabiChin wrote:
Hello,

I noticed that when I dynamically create an array of chars, the
resulting size of the allocated memory block is larger by about 15
bytes than what I specified. Here is example code:

char *createTextBuff er(char *buffer, int length)
{
buffer = new char[length];

if (buffer == NULL) {
return NULL;
}
length = strlen(buffer); // Current buffer shows larger size.
return buffer;
}
strlen is a "C" library function which returns the length of a "null
terminated string". In other words, in the current case, it will count
the number of characters from start of buffer till it finds a null
character. Since char is a basic data type, buffer remains
uninitialized, and thus contains a junk. It is incorrect to relie on
strlen.

The above program causes a crash when destroying the allocated memory
via delete.

This is because usage of new[] must be matched via delete[], not
delete.

Dec 17 '05 #6

"AlabiChin" <al**********@y ahoo.com> wrote in message
news:11******** **************@ g47g2000cwa.goo glegroups.com.. .
Hello,

I noticed that when I dynamically create an array of chars, the
resulting size of the allocated memory block is larger by about 15
bytes than what I specified. Here is example code:

char *createTextBuff er(char *buffer, int length)
{
buffer = new char[length];

if (buffer == NULL) {
return NULL;
}
length = strlen(buffer); // Current buffer shows larger size.


strlen looks for the first null character to determine the end of the
string. Since you have not initialized the array, the array contains random
information, and your length will be some arbitary number.

To see this add this line just before your length =

buffer[0] = '\0';

Now your length will be 0 because it will find the null in the first
position.

When you delete this array you use delete[]
Dec 17 '05 #7
Hmm, I studied documentation in VS 2003.NET which I consider not too
out-of-date and found out that new returns 0/NULL. If you want exception
handling you need to use set_new_handler function.
From what time new throws exception? What type of exception is it?
Dec 17 '05 #8
Viktor Prehnal wrote:
Hmm, I studied documentation in VS 2003.NET which I consider not too
out-of-date and found out that new returns 0/NULL. If you want exception
handling you need to use set_new_handler function.
new throws an exception when it fails
From what time new throws exception? What type of exception is it?


std::bad_alloc
--
Nick Keighley

Dec 17 '05 #9
Viktor Prehnal wrote:
Hmm, I studied documentation in VS 2003.NET which I consider not too
out-of-date and found out that new returns 0/NULL. If you want exception
handling you need to use set_new_handler function.
From what time new throws exception?
In Standard C++ (which is existing since 1998), this has always been the
case.
What type of exception is it?


std::bad_alloc

Dec 18 '05 #10

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

Similar topics

4
2594
by: Franklin Lee | last post by:
Hi All, I use new to allocate some memory,even I doesn't use delete to release them. When my Application exit, OS will release them. Am I right? If I'm right, how about Thread especally on Solaries OS? This means that I use new to allocate memory in one Thread and doesn't use delete to release them.
4
6773
by: PaulR | last post by:
Hi, We have a Server running SLES 8 and 3GB memory, with 1 DB2 instance and 2 active Databases. General info... DB2level = "DB2 v8.1.0.72", "s040914", "MI00086", and FixPak "7" uname -a = Linux galahad 2.4.19-64GB-SMP #1 SMP /etc/sysctl.conf kernel.shmmax=268435456
15
1602
by: berthelot samuel | last post by:
Hi, I'm trying to develop an application for modeling 3D objects from Bezier patches, but I have a memory allocation problem. Here are my structures: typedef struct _vector3 { union { struct {
7
1859
by: Dan Nilsen | last post by:
Hi! I'm writing a small piece of software that basically runs on an embedded system with a Power-PC cpu. This runs on a stripped down version of Linux - Busybox. As I'm writing a piece of code that basically acts as a server and that will be running for weeks or months and probably even longer, memory management is a topic that is quite crucial.
3
3762
by: Florin | last post by:
Hi all, I have a problem related to memory grow on a server application which is basically stateless (I have some static info loaded). The client accesses this server using remoting and it has worked for about 2 years without problems. The problem I have encountered lately is that the memory on server side started to grow and not to be released. I have checked first new functionalities but after isolating these on separate server, the...
74
4709
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...
66
3651
by: Johan Tibell | last post by:
I've written a piece of code that uses sockets a lot (I know that sockets aren't portable C, this is not a question about sockets per se). Much of my code ended up looking like this: if (function(socket, args) == -1) { perror("function"); exit(EXIT_FAILURE); } I feel that the ifs destroy the readability of my code. Would it be
1
7979
by: Peterwkc | last post by:
Hello all expert, i have two program which make me desperate bu after i have noticed the forum, my future is become brightness back. By the way, my problem is like this i the first program was compiled and run without any erros but the second program has a run time error when the function return from allocate and the ptr become NULL. How to fixed this? Second Program: /* Best Method to allocate memory for 2D Array because it's ...
34
2593
by: jacob navia | last post by:
Suppose that you have a module that always allocates memory without ever releasing it because the guy that wrote it was lazy, as lazy as me. Now, you want to reuse it in a loop. What do you do? Contrary to some people that will start crying to that &@@""#~ programmer that wrote this sh!!!! you keep your cool and you do the following:
9
2639
by: Steven Powers | last post by:
Imagine the following setup class Parent { virtual void doStuff(); } class Child : public Parent { virtual void doStuff(); }
0
10648
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
10389
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
10402
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
10135
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
9205
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
7670
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
6890
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();...
1
4339
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
3
3018
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.