What is wrong in this simple code? It works, but valgrind shows errors. How should it look like?
What should be definition of int func(int*)?
main.cpp:
#include <iostream>
#include <stdio.h>
#include <cstdlib>
using namespace std;
int func(int* terminal);
int main()
{
int* x = (int*)malloc(3);
x[0]=1;
x[1]=2;
x[2]=3;
func(x);
}
int func(int *terminal)
{
cout<<(*terminal)<<endl;
cout<<(*terminal+1)<<endl;
cout<<(*terminal+2)<<endl;
return 1;
}
valgrind log:
==2806== Invalid write of size 4
==2806== at 0x80486A6: main (main.cpp:12)
==2806== Address 0x434f028 is 0 bytes inside a block of size 3 alloc'd
==2806== at 0x402A17C: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2806== by 0x804869D: main (main.cpp:11)
==2806==
==2806== Invalid write of size 4
==2806== at 0x80486B3: main (main.cpp:13)
==2806== Address 0x434f02c is 1 bytes after a block of size 3 alloc'd
==2806== at 0x402A17C: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2806== by 0x804869D: main (main.cpp:11)
==2806==
==2806== Invalid write of size 4
==2806== at 0x80486C0: main (main.cpp:14)
==2806== Address 0x434f030 is 5 bytes after a block of size 3 alloc'd
==2806== at 0x402A17C: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2806== by 0x804869D: main (main.cpp:11)
==2806==
==2806== Invalid read of size 4
==2806== at 0x80486F1: func(int*) (main.cpp:22)
==2806== by 0x80486D1: main (main.cpp:16)
==2806== Address 0x434f028 is 0 bytes inside a block of size 3 alloc'd
==2806== at 0x402A17C: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2806== by 0x804869D: main (main.cpp:11)
==2806==
1
==2806== Invalid read of size 4
==2806== at 0x804871A: func(int*) (main.cpp:23)
==2806== by 0x80486D1: main (main.cpp:16)
==2806== Address 0x434f028 is 0 bytes inside a block of size 3 alloc'd
==2806== at 0x402A17C: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2806== by 0x804869D: main (main.cpp:11)
==2806==
2
==2806== Invalid read of size 4
==2806== at 0x8048746: func(int*) (main.cpp:24)
==2806== by 0x80486D1: main (main.cpp:16)
==2806== Address 0x434f028 is 0 bytes inside a block of size 3 alloc'd
==2806== at 0x402A17C: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2806== by 0x804869D: main (main.cpp:11)
==2806==
Maybe I should go fishing instead of studying c++.