473,734 Members | 2,274 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

memory overlap while dynamic initialization using new

17 New Member
this is my code to calculate the sum of digits in a number
for eg. 432567
sum =4+3+2+5+6+7=27
i 'm using turboc++ compiler from borland and i 'm runing my program on DOS.

Expand|Select|Wrap|Line Numbers
  1. #include<iostream.h>
  2. #include<conio.h>
  3. long poweroften(int);     //to calculate power of 10
  4.  
  5.  
  6. void main()
  7. {
  8. clrscr();
  9.   unsigned long number=241526;   //to find the sum of digits as:
  10.                  //2+4+1+5+2+6=20
  11.   unsigned long   numstore=number; //to keep backup of number
  12. unsigned long *quo =new unsigned long[];  //to calculate quotient
  13. unsigned long *rem =new unsigned long[]; //to calc. remainder
  14. int i,sum=0;
  15. cout<<"\n the no. is: "<<number; //to display original number
  16. /*cout<<"\n  quo is pointing to: "<<quo;
  17. cout<<"\n rem is: "<<rem;*/
  18.  for(i=0;number!=0;i++)
  19.    {
  20.      rem[i]=number%poweroften(i+1);   //finding remainder
  21.  
  22.      number-=rem[i];  //substracting the rem from number
  23.      quo[i] = rem[i]/poweroften(i);   //then calculating quotient
  24.      cout<<"\n rem is: "<<(rem+i)<<"\n and quo is: "<<quo+i;
  25.      //cout<<"\n rem is: rem["<<i<<"]"<<rem[i]<<"\t and QUO["<<i<<"]"<<quo[i];
  26.      cout<<"\n  quo is pointing to: "<<quo+i;  //to get the address of quo elements
  27.      cout<<"\n rem is pointing to: "<<rem+i;  //to get the address of rem elements
  28.        getch();
  29.   }
  30.    cout<<"\n and quo[0] is: "<<quo[0]; //it should store 6(the first remainder) but it's value is: 1000 that is rem[2]'s value
  31.                                        // remaining array values are not changed
  32.   for(int j=0;j<i;j++)
  33.      {
  34.          cout<<"\n in the sum loop quo is pointing to: "<<quo;
  35.          cout<<"\n adding "<<quo[j];  // to calculate the sum of quo[] array elements
  36.          sum+=quo[j];
  37.     }
  38. cout<<"\n sum of number: "<<numstore<<" is: "<<sum;//sum is wrong since quo[0] is modified by the compiler
  39. }
  40. long poweroften(int i)
  41. {
  42.    unsigned long prod=1;
  43.   for(int j=0;j<i;j++)
  44.     {
  45.     prod*=10;
  46.     }
  47.     return prod;
  48. }
  49.  
  50.  
quo[0] value is getting overlapped by rem[2]
and if the number is large(for eg- 2146898787) quo[1] and quo[2] are also overlapped by rem[3] and rem[4].
i don't know why it's happening.
Aug 23 '07 #1
14 4263
RRick
463 Recognized Expert Contributor
You're not allocating enough space for quo and rem. You need to pick some number that is greating than the max number of digits you expect to process.

My compiler won't let me say new ... [ ] without a number in between the [ and ]. I'm not sure what is being created, but its not enough. Since you're just using the variables locally, you can define them locally. For example: int quo[20];
Aug 23 '07 #2
rohitkumar
17 New Member
You're not allocating enough space for quo and rem. You need to pick some number that is greating than the max number of digits you expect to process.

My compiler won't let me say new ... [ ] without a number in between the [ and ]. I'm not sure what is being created, but its not enough. Since you're just using the variables locally, you can define them locally. For example: int quo[20];
i think the syntax to allocate memeory to an array dynamically is as follows:
datatype pointer = new datatype[];
eg:
int *p = new int[];
if i am allocating memory dynamically i think the size is not fixed, it is always decided at run time so, i can't put a no. inside [].
we can access the dynamically allocated memory using pointer p;.
about quo[20],this is allocation of memory at compile time.i want to use a variable allocated at the run time which in turn will be dependent on value of the number at run time.

i think it is related to the memory model we are using for eg: tiny,small,comp act,huge etc.
Aug 24 '07 #3
Banfa
9,065 Recognized Expert Moderator Expert
datatype pointer = new datatype[];
eg:
int *p = new int[];
No the syntax to dynamically allocate memory in C++ is

datatype pointer = new datatype[expression];

eg:
Expand|Select|Wrap|Line Numbers
  1. int *p = new int[5];
  2.  
  3. int count = 5;
  4.  
  5. int *p2 = new int[count];
  6.  
Aug 24 '07 #4
rohitkumar
17 New Member
No the syntax to dynamically allocate memory in C++ is

datatype pointer = new datatype[expression];

eg:
Expand|Select|Wrap|Line Numbers
  1. int *p = new int[5];
  2.  
  3. int count = 5;
  4.  
  5. int *p2 = new int[count];
  6.  
then how come this is a dynamic memory allocation if i have to determine the size at run time only.
new is used for allocating memory at runtime depending upon the number of elements and it returns the starting address of heap memory.
my compiler is ok with this type of syntax
int *p = new int[]
now the integer array will be created at run time and any no. of elements will be added to it,till the heap memory gets exhausted.
this is what i interpret,pleas e post the clarification if i am wrong.
thanks in advance.
Aug 24 '07 #5
Banfa
9,065 Recognized Expert Moderator Expert
then how come this is a dynamic memory allocation if i have to determine the size at run time only.
It is dynamic because you can determin the size at runtime if you desire or it can be fixed at compile time.
new is used for allocating memory at runtime depending upon the number of elements and it returns the starting address of heap memory.
my compiler is ok with this type of syntax
int *p = new int[]
Yes exactly but in this syntax you don't provide it with the number of required elements, this generates a request for 0 bytes of memory (if it compiles).

now the integer array will be created at run time and any no. of elements will be added to it,till the heap memory gets exhausted.
No memory is only allocated from the heap in response to an explicit call to new or malloc or calloc or realloc. You allocate 0 bytes of memory and then write multiple values to that unallocated block. You are creating memory corruptions and running a very real risk of a segmentation fault.
Aug 24 '07 #6
rohitkumar
17 New Member
It is dynamic because you can determin the size at runtime if you desire or it can be fixed at compile time.
Yes exactly but in this syntax you don't provide it with the number of required elements, this generates a request for 0 bytes of memory (if it compiles).

No memory is only allocated from the heap in response to an explicit call to new or malloc or calloc or realloc. You allocate 0 bytes of memory and then write multiple values to that unallocated block. You are creating memory corruptions and running a very real risk of a segmentation fault.
Thanks for the detailed reply. now the picture is somewhat clear to me. still one issue is remaining, if ever, i have to use an array whose size cannot be determined at compile time suppose to store student rollnos,then should i use the syntax
int *rollno= new int[100];
considering that max expected no. of students is 100. this will store the starting address of the memory loaction in rollno and provide me with 200 bytes of memory(consider ing int of size 2 bytes on the machine) but i suppose this is wastage of some memory if the no. of students is less than 100.what in the case if number of students >100; i think the pointer will write to some memory locations that will result in some error in my program(if at all those locations are used by my other variables).
there must be some way to allocate memory at the run time and its size must vary with the addition of new values in array. its giving me a really hard time.
also please suggest me a good online tutorial on pointers and memory allocations.
another question is if the compiler does not allocate any memory(
according to you it will return an address and 0 bytes of memory)
for the following syntax;
int *roll=new int[];
then howcome my compiler always shows adderess pointed to by
roll+i. for eg.
if i use the following code:
Expand|Select|Wrap|Line Numbers
  1.  
  2. int *roll = new int[];   // pointer to store the starting address of mem loaction
  3. cout<<"\n LOCATION POINTED BY ROLL IS: "<<roll; 
  4.                              // address stored in roll
  5. // loop to store values in roll array
  6.  
  7. for(int i=0;i<5;i++)
  8.    {
  9.      cout<<"NEXT LOCATION  pointed by roll is: "<<(roll+i);
  10.     *(roll+i)=i+1;               //it stores the value in array elements
  11.    }
  12.  
  13. // now the loop to check values
  14.  
  15. for(i=0;i<5;i++)
  16.   { 
  17.     cout<<"roll is pointing to: "<<(roll+i)<<" and value in array is:"<<*   (roll+i)               // it displays the address along with the values  
  18. }
  19.  
according to u if the memory of 0 bytes is returned how come i m able to store
values in the array.
this pointer thing is really bugging me.but i wanna master this pointer monster.i need ur help.
Aug 24 '07 #7
Banfa
9,065 Recognized Expert Moderator Expert
The trick is rather than use arrays, which is considered poor form in C++ use one of the STL container classes. In this case a vector would probably be the class of choice.

Expand|Select|Wrap|Line Numbers
  1. #include <vector>
  2.  
  3. ...
  4.  
  5. vector<int> rollno;
  6.  
  7. rollno.push_back(6);
  8. rollno.push_back(7);
  9. rollno.push_back(8);
  10.  
This will handle all the memory allocation for you.
Aug 24 '07 #8
rohitkumar
17 New Member
The trick is rather than use arrays, which is considered poor form in C++ use one of the STL container classes. In this case a vector would probably be the class of choice.

Expand|Select|Wrap|Line Numbers
  1. #include <vector>
  2.  
  3. ...
  4.  
  5. vector<int> rollno;
  6.  
  7. rollno.push_back(6);
  8. rollno.push_back(7);
  9. rollno.push_back(8);
  10.  
This will handle all the memory allocation for you.
according to you it will return an address and 0 bytes of memory)
for the following syntax;
int *roll=new int[];
then howcome my compiler always shows adderess pointed to by
roll+i. for eg.
if i use the following code:

Code: ( text )
int *roll = new int[]; // pointer to store the starting address of mem loaction
cout<<"\n LOCATION POINTED BY ROLL IS: "<<roll;
// address stored in roll
// loop to store values in roll array

for(int i=0;i<5;i++)
{
cout<<"NEXT LOCATION pointed by roll is: "<<(roll+i) ;
*(roll+i)=i+1; //it stores the value in array elements
}

// now the loop to check values

for(i=0;i<5;i++ )
{
cout<<"roll is pointing to: "<<(roll+i) <<" and value in array is:"<<* (roll+i) // it displays the address along with the values
}


according to u if the memory of 0 bytes is returned how come i m able to store
values in the array.
this pointer thing is really bugging me.but i wanna master this pointer monster.i need ur help.

--------------------------------------------------------------------------------
Aug 24 '07 #9
JosAH
11,448 Recognized Expert MVP
For the new[]() operator you just need a primary expression which can be anything
as long as its value is an int value, so:

Expand|Select|Wrap|Line Numbers
  1. int i= 41;
  2. int* ip= new[i+1]; // <--- see? dynamically calculated
  3. ip[0]= 42;
  4. ip[1]= 54;
  5.  
The fact that your compiler accepts things like this:

Expand|Select|Wrap|Line Numbers
  1. int* ip= new int[];
  2.  
... shows that the compiler is quite old and it mistakes int[] for *int; you should
upgrade to a later compiler version.

kind regards,

Jos
Aug 24 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

12
4750
by: natkw1 | last post by:
Hi, I'm attempting to understand the use of pointers(at least grasp how pointers work). I've read the FAQ on http://www.eskimo.com/~scs/C-faq/s6.html on pointers and arrays but I'm still a bit lost. I written the following code to try to understand it but it's not working:
2
952
by: Anthony Nystrom | last post by:
I am looking for some sample code that will give me the amount of memory my app is using at any given moment.... Anyone help? Thanks, Anthony Nystrom
1
2259
by: nasirmajor | last post by:
Dear All, being a new to asp.net i want any guidence, ariticle or sample releating dynamic menu using sqlserver database. where to start. Any help Thanks In advance
15
1404
by: Dilip | last post by:
The subject is a bit misleading because I really can't figure out what the following code snippet is doing and would appreciate any help in deciphering it. I mean I can understand code-wise what is going on but I am missing the larger picture. In what circumstances would I use this? template<typename T>
6
4818
by: Peter Herath | last post by:
I want to create a dynamic report using a crosstab query...... pls someone look into my attached example database and help me out to do the report generation.... example is like dis...: there are 4 combo boxes.. when u select an item from each combo box and click the ViewReport Button then those selected item values should go as parameters to the crosstab query in the vba code subroutine and from that the report should be generated. pls...
1
1647
by: niteshpanchal | last post by:
Hi, How to assign dynamic array using pointers for string.
5
1966
by: Triple-DES | last post by:
I've seen this question raised more than once, but I have not yet seen a definite, conclusive answer. Consider the following code: struct C { C() {} // might throw }; int main() { try { static C c;
8
1770
by: bukzor | last post by:
I want to make a MixIn class that waits to initialize its super- classes until an attribute of the object is accessed. Not generally useful, but desirable in my case. I've written this, and it works, but would like to take any suggestions you guys have. I've commented out the "delattr" call because it throws an AttributeError (although I don't know why). class LateInitMixIn(object):
0
786
by: Priyanka Mane | last post by:
I am creating project : name: hardware detection tools How to detect the user accounts, ups and memory on your computer using vb.net ?
0
8948
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
8780
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9315
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
9186
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
8190
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
6742
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
4553
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
4816
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2733
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.