views:

128

answers:

3

I have a C code in which I have a structure declaration which has an array of int[576] declared in it.

For some reason, i had to remove this array from the structure, So I replaced this array with a pointer as int *ptr; declared some global array of same type, somewhere else in the code, and initialized this pointer by assigning the global array to this pointer. So I did not have to change the way I was accessing this array, from other parts of my code.

But it works fine/gives desired output when I have the array declared in the structure, but it gives junk output when I declare it as a pointer in the structure and assign a global array to this pointer, as a part of the pointer initialization.

All this code is being run on MS-VC 6.0/Windows setup/Intel-x86.

I tried below things:

  1. Suspected structure padding/alignment but could not get any leads? If at all structure alignment could be a culprit how can i proceed to narrow it down and confirm it?

  2. I have made sure that in both cases the array is initialized to some default values, say 0 before its first use, and its not being used before initialization.

  3. I tried using global array as well as malloc based memory for this newly declared array. Same result, junk output.

How can I zero in on the problem? Any pointers would be helpful.

+3  A: 

try to (clean and) rebuild your project, it's possible that existing object files are still accessing your array elements as if it's not allocated on the heap which causes your problems.

Omry
@Omry: I have done clearn build, rebuild after the changes.
goldenmean
try to create a minimal example that demonstrates the problem. by the time you have it you will probably know what you've done wrong. if not just add it to the question.
Omry
+3  A: 

Is it possible you are using sizeof anywhere on the structure field? sizeof(int[576]) != sizeof(int*).

This should be the only visible difference between the two.

EFraim
Although i use sizeof(structure) for allocating memory for that structure, For debugging purposes, i also tried by keeping the array within the structure as it is and then declaring another pointer in that structure and then making that pointer point to that array. So essentially tried to make sure, sizeof did not go awry. Still same result, bad output.
goldenmean
@EFraim: thanks. there is some sizeof going awry in some mecpy in my code.
goldenmean
+1  A: 

You say you did not have to change the way you was accessing this array. But there are some operations that have different results for arrays and pointers. One is the already mentioned sizeof(struct.arr) vs. sizeof(struct.ptr), another is &struct.arr vs. &struct.ptr. Have you checked any single access to this array that anything takes these differences into account?

Secure