473,395 Members | 2,446 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

A 2D array wrapped in a structure

44
Hello

This piece of code works. But earlier, I had tried using (res->data[i][j]) in place of p[i][j (in line 40, in the for loop inside main()). And the program used to fail due to an access violation error.

Then I declared the variable **p within main() and assigned res->data to it. And it worked. Can anyone tell me why using res->data[i][j] didnt work. If u can, please do.

Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h>
  2. //compiled using gcc 3.4.5
  3. struct sam
  4. {
  5. int **data;
  6. };
  7.  
  8. struct sam* func()
  9. {
  10. int rows=2, columns=2, i, j;
  11. struct sam r;
  12. r.data=(int **)malloc(sizeof(int*)*rows);
  13. for(i=0; i<rows; i++)
  14.  {
  15.   r.data[i]=(int*)malloc(sizeof(int)*columns);
  16.  }
  17. for(i=0; i<rows; i++)
  18.  for(j=0; j<columns; j++)
  19.  {
  20.  r.data[i][j]=i+j;
  21.  }
  22. for(i=0; i<rows; i++)
  23.  for(j=0; j<columns; j++)
  24.  {
  25.  printf("%d", r.data[i][j]);
  26.  }
  27. return &r;
  28. }
  29.  
  30. main()
  31. {
  32. int i, j, rows=2, columns=2, **p;
  33. struct sam *res;
  34. res=func();
  35. p=res->data;
  36. printf("\nIn caller");
  37. for(i=0; i<rows; i++)
  38.  for(j=0; j<columns; j++)
  39.  {
  40.  printf("%d", p[i][j]); 
  41.  } 
  42.  
  43. }
Thank you!
Oct 18 '09 #1
6 5736
Banfa
9,065 Expert Mod 8TB
The problem is that although you allocate the data for the int** pointer in struct sam r; in func the structure itself is on the stack and only has the lifetime of the function call. You return a pointer to r but by the time the receiving code gets that pointer the struct sam r no longer exists, it was deleted when func returned.


Never EVER return a pointer to data that is local to the function being called.
Oct 18 '09 #2
hanaa
44
If thats the case then p[i][j] should not work too, because its the value of res->data that has been assigned to it. But using p[i][j] shows me the correct values.
Oct 19 '09 #3
Banfa
9,065 Expert Mod 8TB
The short answer is that I don't have to. As soon as you accessed an invalid pointer you invoked undefined behaviour. As soon as you invoke undefined behaviour all bets are off, anything can happen including apparently correct behaviour.

However I will say more but before I do I must stress that you should not rely on this behaviour because of the reason I stated in my first paragraph.

The thing is that while res points to a structure that has been destroy, res->data points to data that has been malloc'd (and in fact you leak that memory by never freeing it). If you use res directly then the first printf call writes, legitimately to the piece of stack that res points to destroying the contents of *res and causing the access violation.

When you use the line

p=res->data;

before any other code has been executed to dereference res and copy the malloc'd memory pointer before that value is over written which it is the very next line with a printf function call. So p points to valid malloc'd data while res points to invalid stack data that has been overwritten.
Oct 19 '09 #4
hanaa
44
@Banfa
But the field 'data' is a part of the structure res. So if res gets destroyed because its a local variable, the contents of the 'data' field should also be destroyed right.. Or is it because data points to malloc'd memory that it is not destroyed?
Oct 19 '09 #5
Banfa
9,065 Expert Mod 8TB
Yes. The field data is destroyed, in fact that is the only thing that is destroyed the content pointed to by res. However data is only a pointer, destroying the pointer does not destroy what it points to.
Oct 19 '09 #6
hanaa
44
Thank you Banfa. That helped a lot.
Oct 20 '09 #7

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

Similar topics

15
by: lawrence | last post by:
I wanted to test xml_parse_into_struct() so I took the example off of www.php.net and put this code up on a site: <?php $simple = <<<END <item>
5
by: Robert | last post by:
Hi, This might be a strange question but i would like to know how to return an array from a function. Do you have to use pointers for this? Thanks in advance, Robert
36
by: Eric Laberge | last post by:
Hi! I'm working on automatically generated code, and need to assign arrays. memcpy is an obvious solution, but it becomes complicated to use in the context I'm working on, ie.: I could use it...
6
by: Carl | last post by:
Hi, I want to pass an array of object of different type to a function and use it in the function. I am not able to have it working. Function that create the array... public virtual DataSet...
1
by: Matt | last post by:
What is the major differences between array and collection? For example, ArrayList. When to use which? I think array is static container, but collection is dynamic container. The drawback of array...
2
by: Phil Lee | last post by:
What's the general opinion on which of these to choose? I see that the SoapDocumentServiceAttribute defaults to literal/wrapped, but this article -...
2
by: gregory_may | last post by:
Is there a way in VB.Net to declare a local variable that will manipulate an array element .... kind of like an item pointer to a global array?
16
by: pkoniusz | last post by:
Hello everybody, Been just thinking how actually one could convert the following unmanaged code to the managed C++: struct JustAnExample { char value1; int value2; // etc ....
7
by: repekto.argosoft | last post by:
Hi, I'm working with Marshalling. I got an idea to pass an object to the Native side as a byte array i.e. as void* in terms of C. For example: I have a .NET structure Point that contains...
5
by: emmanuel.rivoire | last post by:
Hello, I spent almost a week to be able to embed Python within my C++ game engine. I wrote a mini-tutorial of what I was able to do so far here :...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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
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
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
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...
0
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...

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.