0

An Example demonstrating Passing an array as argument

#include <iostream>
#include <malloc.h>
using namespace std;

typedef unsigned char U8;

#define MAX_LEN 20

void func1(U8* arr)
{
 printf(" Passing Base address Element1 = %s\n",arr);    
}     

void func2(U8* arr)
{
 printf(" Passing Pointer address Element1 = %s \n",arr);    
}

int main()
{

 U8 arr[MAX_LEN] = "Stack Overflow\n";
 U8* arr1 = (U8*)malloc(sizeof(MAX_LEN));
 func1(arr); /* Passing Base address */
 memcpy(arr1,arr,sizeof(arr));
 /*      
 memcpy(arr1,arr,sizeof(MAX_LEN)); Leads to Heap Corruption why ?
 */
 func2(arr1);/* Passing pointer */
 free(arr1); 
 cout << "Array Freed" << endl;
 cin.get();   
 return 0;   
}

Queries : 1. which is the best Practise in consideration with data Processing.[data on stack or Heap] 2. Please suggest reliable methodology to be used for such cases

Prag Rao
  • 1,411
  • 3
  • 11
  • 10

2 Answers2

1
memcpy(arr1,arr,sizeof(MAX_LEN)); // Leads to Heap Corruption why ?

Because sizeof(MAX_LEN) is equivalent to sizeof(20) which is equivalent to sizeof(int). This means you'll copy 4 or 8 bytes (depending on your platform). In fun1 you then print the array as if it were a null terminated string. There is no null terminator though, since you didn't copy it and printf happily runs out of bounds.

sizeof(arr), on the other hand, gives you correct size of 20.

sizeof operator queries the size of the type of the expression you give it as operand, not the value. It's purely compile time operator. The type of integer literal 20 is int and it'll return the size of that type.

jrok
  • 54,456
  • 9
  • 109
  • 141
  • Hi Jrok !! Thanks for your comment !! I am confused bit Now !! Please respond to this one When i declare a Macro its Expanded rit when i write sizeof(MAX_LEN) it should be sizeof(20). am i correct .. then why it allcoates size as 4 . And as my array is U8... 1 byte whts wrong ? I checked it in my compiler : its surprsing .. Output printf("Arr Len = %d",sizeof(arr)); printf("Max Len = %d",sizeof(MAX_LEN)); Arr Len = 20 Max Len = 4 – Prag Rao Oct 25 '13 at 11:38
0

Honestly? If you write in C++, simply use std::vector, pass it by reference and forget about the whole problem.

If you really have to use C-style arrays, I'd say, that in most cases (I mean, 99.9%), you'll have to allocate the array on the heap, because programs usually have limited stack memory available and placing an array there is generally not a good idea.

Remember though, that constant text expressions defined in the following way:

const char * myText = "Alice has a cat";

may not be stored on the stack, but somewhere (depending on C++ compiler). These won't occupy place on the stack and mostly probably this is the case in your example. In this example, a pointer to that text is stored on the stack, but the text itself is (mostly probably) stored elsewhere.

Spook
  • 25,318
  • 18
  • 90
  • 167