haris
haris

Reputation: 159

How to create a new char array in NASM assembly using malloc

Given this c code:

char** names=(char**)malloc(count*sizeof(char*));

I want to convert it to NASM assembly code. Here is what I tried, but the code crashes:

  mov eax, dword count
  mov ebx, [eax*4] ;; i did times 4 because we clear stack by 4 bits or bytes?
  push ebx
  call _malloc
  mov names, eax
  add esp, 4

What does sizeof(char*)mean? which char pointer is the code addressing?

Upvotes: 0

Views: 668

Answers (3)

Heath Hunnicutt
Heath Hunnicutt

Reputation: 19457

It would be interesting to know more about how it crashes. On which instruction?

To answer your question sizeof(char *) means the size of any char * -- they are all the same size. 32-bit pointers are 4 bytes long, 64-bit pointers are 8 bytes long.

The code isn't dereferencing any pointer inside sizeof(). It's evaluated at compile-time and results in the size required to store a pointer of type char *.

Upvotes: 1

Jester
Jester

Reputation: 58762

The reason it crashes is because mov ebx, [eax*4] is accessing memory at address eax * 4 which is unlikely to be valid, and definitely not what you want anyway. To multiply by 4, you can use lea ebx, [eax*4] or shl eax, 2 then push eax.

PS: Learn to use a debugger.

Upvotes: 3

wallyk
wallyk

Reputation: 57764

sizeof (char *)

returns the size of a pointer:

  • 16 bits [2 bytes] for a near (small model) pointer
  • 32 bits [4 bytes] for a large or huge model in real mode, or a pointer in 32-bit virtual mode
  • 64 bits [8 bytes] for a pointer in 64-bit mode.

Upvotes: 1

Related Questions