2

What's wrong with this little program? I cannot get the correct answer. I just use m[1][1] to test but it's always 0!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    int **m;
    m = new int*[5];
    for( int i = 0 ; i < 5; i++ )
    {
        m[i] = new int[5];
        memset(m[i],1,sizeof(int)*5);   
    }

    printf("%f",*(*(m+1)+1));
    return 0;

}
1
  • 1
    Passing the wrong type to a variadic function is undefined behaviour. Commented Apr 17, 2013 at 0:21

1 Answer 1

4

This is "not C++". Yes, it's a C++ code, but it isn't using reasonable C++ idioms -- you're mixing C-style memset and pointer chasing with operator new (which is the only C++ feature you hapen to use). I will therefore assume that you have a reason to use code like that. If you don't have that, seriously consider using some STL class like a vector and avoid pointer manipulation.

If you used a reasonable compiler and added reasonable warnings, you would get the error immediately:

$ g++ -Wall pwn.cpp
pwn.cpp: In function ‘int main()’:
pwn.cpp:14:28: warning: format ‘%f’ expects argument of type ‘double’, but argument 2 has type ‘int’ [-Wformat]

The correct argument to printf for printing ints is %d. How does it look after changing that?

$ ./a.out 
16843009

How come it doesn't print 1? The memset function sets memory, it does not initialize integers. And indeed, 0x01010101 == 16843009. This is not portable and very likely not what you want to do. Just don't do this, seriously.

Sign up to request clarification or add additional context in comments.

2 Comments

Declaring variables after calling functions is also C++. for (int i = 0; i < 5; i++) is invalid in C, because you can't declare i there.
@Havenard mixing variable declarations and code (as the int i inside the for loop) is actually valid C99 code. You are right in that this was not allowed in earlier versions of the C standard, thanks for pointing that out. References: gcc says error: ‘for’ loop initial declarations are only allowed in C99 mode and note: use option -std=c99 or -std=gnu99 to compile your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.