0

How does Variable Length arrays (VLA) take space in memory?

I have observed that VLAs do not take continuous memory space, can anyone please confirm the same??

void func(const IplImage *imgSrc, IplImage *imgDest)
{
  uchar *data = (uchar *)imgSrc->imageData;      

  // get the image data
  int height    = imgSrc->height;
  int width     = imgSrc->width;
  int step      = imgSrc->widthStep;
  int stepSobel = imgDest->widthStep;

  //Calculate Sobel of Image  
  uchar *dataSobel = (sobelStart + stepSobel);  

  //**Declaration of VLAs**
  int prevRowBuf[width],curRowBuf[width],nextRowBuf[width];

  for(int j=1;j<(width-1);j++)
  {    
    prevRowBuf[j] = data[j+1]-data[j-1];
    curRowBuf[j]  = data[step+j+1]-data[step+j-1];
  }

  // Some opencv processing
    for() // Some Conditions
    {

        //memcpy(prevRowBuf,curRowBuf,width);
        //memcpy(curRowBuf,nextRowBuf,width);

        //Replaced with
        for(int i=0 ; i< width; i++)
        {
          prevRowBuf[i]=curRowBuf[i];
          curRowBuf[i]=nextRowBuf[i];
        }
    } 
 }

With the two memcpy operations, my program was working only for few starting indexes of VLAs. But after replacing the memcpy with for Loop my program is working fine for all the indexes of VLAs.

techbull
  • 118
  • 2
  • 16
  • 2
    In C++ there are no variable length arrays. If I remember correctly, gcc allows them as an extension. – Pete Becker Jun 26 '13 at 10:48
  • 1
    Only C99 has VLA! C++ and other versions of C might have it as compiler extension (which means VLA is not really a part of the language, rather it is a feature provided by your compiler). – Nawaz Jun 26 '13 at 10:49
  • `memcpy(prevRowBuf,curRowBuf,width);` copies `width` _bytes_, not `width` `int`s. You need `memcpy(prevRowBuf,curRowBuf,width * sizeof curRowBuf[324]);` (the `324` is of course arbitrary, you could also use `0`, or `-3`, or `INT_MAX`). – Daniel Fischer Jun 26 '13 at 12:04
  • @DanielFischer: Thanks for the response. Program working fine now... :D – techbull Jun 26 '13 at 12:09

1 Answers1

4

First off, C++ has no VLAs. GCC implements them as a nonstandard extension.

Now, to answer your question in the context of said GCC extension:

I have observed that VLAs do not take continuous memory space, can anyone please confirm the same?

No, that is wrong. VLAs will take up continuous space. That space usually (always?) comes from the stack rather than the heap memory, just like statically sized C arrays.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214