lucas.fonseca
lucas.fonseca

Reputation: 21

How to properly do dynamic memory allocation (C++)

I am trying to create a dynamically allocated array and print it's contents in C++. Although my code is producing incredibly strange output when I print.

int main() {
    int* arr;

    arr = new int [1200];
    memset(arr, 5, 1200);

    for (int i = 0; i < 1200; i++)
        printf("%d ", arr[i]);

    std::cout << '\n';
    return 0;
}

Mixing the cout and printf was just because I was playing around with the code. All the proper includes are in my file.\

Here is the output:

84215045 84215045 84215045 84215045 84215045 84215045 84215045 84215045 84215045 84215045 84215045 84215045 1285 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 

I have no idea how this was produced.

EDIT:

Thank you everyone for the answers. I now understand what my code does and why the output looks the way that it look.Great answers.

Upvotes: 0

Views: 107

Answers (3)

Stefano Sanfilippo
Stefano Sanfilippo

Reputation: 33046

Consider 84215045 byte by byte in hex and you will understand what happened:

84215045 = 05050505 (hex)

memset initializes every byte to 5, but an integer is 4-byte long in your case. Also, memset expects the size in bytes of the memory region to fill, which is not 1200, but 1200 * sizeof (int), which in your case appears to be 4800. This explains the trailing zeroes as well.

You might initialize every element to 5 using a loop:

arr = new int [1200];
for (int i = 0; i < 1200; ++i) arr[i] = 0;

or with pointers:

arr = new int[1200];
for (int *cur = arr, *end = arr + 1200; cur < end; ++cur) *cur = 0;

Finally, consider doing away with direct allocation of arrays with new and using STL containers like std::vector if possible.

Upvotes: 2

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145269

Your code is setting each byte in the first part of the array, to 5. With a modern C++ compiler as of 2014 each int is 4 bytes or 8 bytes, with each byte 8 bits (although on some computers it can be 16 bits per byte). Assuming 8 bits per byte and 4 bytes per int you'd get the value ((5×256 + 5)×256 + 5)×256 + 5 =

C:\> set /a ((5*256 + 5)*256 + 5)*256 + 5
84215045
C:\> _

Here's how to do your program in the most natural way in C++:

#include <iostream>
#include <vector>
using namespace std;

auto main() -> int
{
    vector<int> arr( 1200, 5 );
    for( int x : arr ) { cout << x << ' '; }
    cout << '\n';
}

Upvotes: 2

David Schwartz
David Schwartz

Reputation: 182761

memset(arr, 5, 1200);

If you scribble a whole bunch of 5'a on a piece of paper and then try to read the paper, you'll get back things like "5555". 84215048 in hex is 0x05050505.

Don't manipulate arrays of data as if they were raw chunks of memory unless you know exactly what you're doing.

Upvotes: 2

Related Questions