473,499 Members | 1,716 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How can a int pointer stores more than one int

8 New Member
Hi all,

This might be a small query but imp for me. I have put my ideas in comments in below prog.

My idea is if i am assigning memory for one int how can i store there 10 elements of int. Is this type of storing elements is safe.



Expand|Select|Wrap|Line Numbers
  1. int main(int argc, char* argv[])
  2. {
  3.  
  4.     int*p = NULL;
  5.     p = new int;  // here i guess i am assigning only 4 byte memory that is for one int
  6.     int * q = NULL;
  7.     abc(p);
  8.  
  9.     def(p);
  10.  
  11.     return 0;
  12. }
  13.  
  14. void abc(int* p)
  15. {
  16.   for(int i = 0;i < 10;i++)
  17.     {
  18.  
  19.         *(p+i)     = 10; // But here I can store 10 elements how other mem are allocated
  20.     }
  21.  
  22.  
  23.  
  24. }
  25. void def(int* p)
  26. {
  27.  
  28.   for(int i = 1;i < 10;i++)
  29.     {
  30.  
  31.       printf("values are : %d \r\n",*(p+i))    ; // also here i can print those value
  32.     }
  33.  
  34. }
  35.  
  36.  

Please suggest.

Thanks
Dec 30 '08 #1
10 1708
Aftabpasha
32 New Member
No, its not safe. You are allocating memory for only one integer, but you are storing 9 more values at next 9 integer locations from valid allocated address.
It may cause Segmentation Fault. You can't predict about it. Ideally they are invalid.
Kind Regards.
Aftab
Dec 30 '08 #2
kishore84
8 New Member
Thanks for ur reply. But i have seen often this typeof code wriiten by some proggramres(they are some exp people :)). and also same way we can delare a char* for only one char but can store more than one value . I myself seen they are working for some thousands byte. But don't why this is allowed at all.

I need some more words from u guys on this topic.....some elaboration will highly apreciated...


Thanks
Dec 30 '08 #3
Aftabpasha
32 New Member
It's certainly dangerous to work on unallocated memory. You can't predict when there will be Segmentation Fault. It may work sometimes because OS allocates memory in blocks for increasing efficiency. Though you want only 4 bytes, it may give you more (e.g. 512 bytes block). So your program still have some memory left as unused after using your 4 bytes. So, it will not show you error. But as I said its unpredictable and should be avoided. Handling memory safely is a good programming practice.
Kind Regards,
Aftab
Dec 30 '08 #4
YarrOfDoom
1,247 Recognized Expert Top Contributor
I think when you do this, you're writing at valid memory locations, but these locations aren't reserved for those ints. So it is very much possible you're overwriting other values there, or when you reserve space later, it gets put there, thus overwriting your ints.
Dec 30 '08 #5
kishore84
8 New Member
Ur answers are really helpfull. will all compilers allow this type of operations at all.
U people are right i think because this loop is not working when i incresed the i value. To be more specific for my machine it works upto 6600 (here int size is 4 bytes) some thing like below

Expand|Select|Wrap|Line Numbers
  1. for(int i = 0;i < 6600;i++)
  2.     {
  3.  
  4.         *(p+i)     = 10; // it works upto 6600
  5.         //q = p+i;
  6.     }
  7.  
I don't know what is this magical number 6600. After that it gives unhandled exception. so i guess it is aprox 25 kb. then what abt 512 byte (as earlier told by Aftabpasha).

please suggest.....



Thanks
Dec 30 '08 #6
Banfa
9,065 Recognized Expert Moderator Expert
You should not try to explain the magical 6600 it is not really worth the effort. Once you wrote outside the area of allocated memory you invoked undefined behaviour. That means anything could happen, that it only appears to seg fault (raise an exception) after 6600 is fairly irrelevant, on a different platform or uder different circumstances it might seg fault at 2.

All compilers will allow this operation because if you examine each line individually there is nothing wrong with any given line of code, it is only when you combine them together and write outside the area of memory you allocated that you have a problem.

Try combining your code with additional memory allocations and writes (both before and after your allocation) and you will see more problems.

Basically never write to memory addresses that do not have memory (or hardware) explicitly assigned to them.
Dec 30 '08 #7
kishore84
8 New Member
Good insight in the subject. Thanks all for ur time.


thanks
Dec 30 '08 #8
freelance programmer
11 New Member
In embedded system , you may not get 10 bytes extra .
Dec 30 '08 #9
Aftabpasha
32 New Member
512 bytes was just an example. It mainly depends upon your platform, available memory, your requested memory etc. You can search for "Buddy Memory Allocation" or just "Dynamic Memory Allocation" in Wikipedia for more information.

Kind Regards,
Aftab
Dec 30 '08 #10
weaknessforcats
9,208 Recognized Expert Moderator Expert
No one has yet mentioned decay of array. This is caused by C/C++ in passing arrays to functions. Only the address is passed so from inside the function, the number of elements is not known.
Read this insight: Arrays Revealed.
Dec 31 '08 #11

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

Similar topics

10
2034
by: Chris Mantoulidis | last post by:
I see some really weird output from this program (compiled with GCC 3.3.2 under Linux). #include <iostream> using namespace std; int main() { char *s; s = "test1"; cout << "s = " << s << "...
11
15747
by: Rajesh | last post by:
Dear All, Please let me know the advantage of function pointer? Is it fast calling function using function pointer? Is it possible to use function pointer to optimise code? Thanks and regards...
9
15704
by: sangeetha | last post by:
Hello, Is there any performance difference in using of the following two declaration? int (*ptr); //Array of 10 int pointers int *ptr; // pointer-to-array of 10. Regards, Sangeetha.
8
1444
by: kathy | last post by:
If I have 2D array like: int **p; p = new int*; for(int i=0;i<10;i++) { p = new int; }
51
4390
by: Kuku | last post by:
What is the difference between a reference and a pointer?
3
5349
by: jagguy | last post by:
hi could someone tell me a good website that explains pointer to pointers well. Not just simple stuff like 2d arrays passing , or pointing to another int variab.le
7
3430
by: iamchiaweilin | last post by:
Hello all: What's the difference between p and q in the following statements? char p = "Hello"; char *q = "Hello"; I know q stores the address of 'H'. Question is: does p store the...
11
2343
by: toton | last post by:
Hi, all of the containers in STL stores object itself (thus copy contsructability & assignability is needed), while NTL or boost ptr_container stores pointer to the object in the container (either...
4
1444
by: jthep | last post by:
If I have a pointer say int **pa that stores the address to another pointer int *pb, pa would be storing the address of pb which contains an address to lets say int c = 10. Picking an arbitrary...
41
2792
by: simonl | last post by:
Hi, I've been given the job of sorting out a crash in our product for which we have the crash information and an avi of the event (which can't possibly match but more of that later...) (btw this...
0
7128
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
7169
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,...
0
7215
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
7385
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
5467
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,...
0
4597
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...
0
3096
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...
1
661
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
294
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...

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.