Is the following code legal?
char* randomMethod1() {
char* ret = "hello";
return ret;
}
and this one?
char* randomMethod2() {
char* ret = new char[10];
for (int i = 0; i < 9; ++i) {
ret[i] = (char)(65 + i);
}
ret[9] = '\0';
return ret;
}
I'd say the first one is legal, as what you are actually doing is returning a pointer to a string literal that I think is loaded from the string table of the program. However, I'd say the second is not. I'd say in the second method you are allocating memory on the stack, which as soon as you leave the function, might be used by another method, turning to trash the pointer you are returning. How is that it really works?
edit: Ok, here is the disassembled code. Could anyone explain me how can I see it is being allocated on the heap?
char* randomMethod2() {
000536E0 push ebp
000536E1 mov ebp,esp
000536E3 sub esp,0E4h
000536E9 push ebx
000536EA push esi
000536EB push edi
000536EC lea edi,[ebp-0E4h]
000536F2 mov ecx,39h
000536F7 mov eax,0CCCCCCCCh
000536FC rep stos dword ptr es:[edi]
char* ret = new char[10];
000536FE push 0Ah
00053700 call operator new (511E0h)
00053705 add esp,4
00053708 mov dword ptr [ebp-0E0h],eax
0005370E mov eax,dword ptr [ebp-0E0h]
00053714 mov dword ptr [ret],eax
for (int i = 0; i < 9; ++i) {
00053717 mov dword ptr [i],0
0005371E jmp randomMethod2+49h (53729h)
00053720 mov eax,dword ptr [i]
00053723 add eax,1
00053726 mov dword ptr [i],eax
00053729 cmp dword ptr [i],9
0005372D jge randomMethod2+5Fh (5373Fh)
ret[i] = (char)(65 + i);
0005372F mov eax,dword ptr [i]
00053732 add eax,41h
00053735 mov ecx,dword ptr [ret]
00053738 add ecx,dword ptr [i]
0005373B mov byte ptr [ecx],al
}
0005373D jmp randomMethod2+40h (53720h)
ret[9] = '\0';
0005373F mov eax,dword ptr [ret]
00053742 mov byte ptr [eax+9],0
return ret;
00053746 mov eax,dword ptr [ret]
}
00053749 pop edi
0005374A pop esi
0005374B pop ebx
0005374C add esp,0E4h
00053752 cmp ebp,esp
00053754 call @ILT+320(__RTC_CheckEsp) (51145h)
00053759 mov esp,ebp
0005375B pop ebp
0005375C ret