Y
Y
Yarik Mamaev2017-08-21 12:02:46
Programming
Yarik Mamaev, 2017-08-21 12:02:46

Does indexing of the array of command line argument pointers start from 1 or from 0?

To be precise, I'm concerned about the line mem_size = atoi(argv[1]);

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
  char *char_ptr;  // Указатель на символьный тип
  int *int_ptr;    // Указатель на целый тип
  int mem_size;

  if (argc < 2)		// Если нет аргументов командной строки,
    mem_size = 50;  // исползуется 50 - значение по умолчанию
  else
    mem_size = atoi(argv[0]);

  printf("\t[+] allocating %d bytes of memory on the heap for char_ptr\n", mem_size);
  
  char_ptr = (char *) malloc(mem_size);  // Выделение памяти в куче

  if(char_ptr == NULL)    // Проверка ошибки сбоя функции malloc()
  {
    fprintf(stderr, "Error: could not allocate heap memory.\n");
    exit(-1);
  }

  strcpy(char_ptr, "Thes is memory is located in the heap.");
  printf("char_ptr (%p) --> '%s'\n", char_ptr, char_ptr);

  printf("\t[+] allocating 12 bytes of memory on the heap for Int_ptr\n");
  int_ptr = (int *) malloc(12);  // Еще раз выделяем память в куче

  if(int_ptr == NULL)
  {
    fprintf(stderr, "Error: could not alllocate heap memory.\n");
    exit(-1);
  }

  strcpy(char_ptr, "new memory");
  printf("char_ptr (%p) --> '%s'\n", char_ptr, char_ptr);

  printf("\t[-] freeing int_ptr's heap memory...\n");
  free(int_ptr);  // Освободить память в куче
  printf("\t[-] freeing char_ptr's heap memory..\n");
  free(char_ptr); // Освободить еще один блок памяти в куче
}

PS I tried with 1 and 0 to run the program. Works this way and that. But if I start typing something after calling the program from 0 like ./tree.out 123 , then the program crashes
[email protected]:~$ ./tree.out 0913
  [+] allocating 0 bytes of memory on the heap for char_ptr
char_ptr (0x1702420) --> 'Thes is memory is located in the heap.'
  [+] allocating 12 bytes of memory on the heap for Int_ptr
char_ptr (0x1702420) --> 'new memory'
  [-] freeing int_ptr's heap memory...
*** Error in `./tree.out': free(): invalid next size (fast): 0x0000000001702440 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7ffa970a17e5]
/lib/x86_64-linux-gnu/libc.so.6(+0x8037a)[0x7ffa970aa37a]
/lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7ffa970ae53c]
./tree.out[0x400892]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7ffa9704a830]
./tree.out[0x400649]
======= Memory map: ========
00400000-00401000 r-xp 00000000 08:01 20578604                           /home/king/tree.out
00600000-00601000 r--p 00000000 08:01 20578604                           /home/king/tree.out
00601000-00602000 rw-p 00001000 08:01 20578604                           /home/king/tree.out
01702000-01723000 rw-p 00000000 00:00 0                                  [heap]
7ffa90000000-7ffa90021000 rw-p 00000000 00:00 0 
7ffa90021000-7ffa94000000 ---p 00000000 00:00 0 
7ffa96e14000-7ffa96e2a000 r-xp 00000000 08:01 25301471                   /lib/x86_64-linux-gnu/libgcc_s.so.1
7ffa96e2a000-7ffa97029000 ---p 00016000 08:01 25301471                   /lib/x86_64-linux-gnu/libgcc_s.so.1
7ffa97029000-7ffa9702a000 rw-p 00015000 08:01 25301471                   /lib/x86_64-linux-gnu/libgcc_s.so.1
7ffa9702a000-7ffa971ea000 r-xp 00000000 08:01 25301433                   /lib/x86_64-linux-gnu/libc-2.23.so
7ffa971ea000-7ffa973ea000 ---p 001c0000 08:01 25301433                   /lib/x86_64-linux-gnu/libc-2.23.so
7ffa973ea000-7ffa973ee000 r--p 001c0000 08:01 25301433                   /lib/x86_64-linux-gnu/libc-2.23.so
7ffa973ee000-7ffa973f0000 rw-p 001c4000 08:01 25301433                   /lib/x86_64-linux-gnu/libc-2.23.so
7ffa973f0000-7ffa973f4000 rw-p 00000000 00:00 0 
7ffa973f4000-7ffa9741a000 r-xp 00000000 08:01 25301405                   /lib/x86_64-linux-gnu/ld-2.23.so
7ffa975fa000-7ffa975fd000 rw-p 00000000 00:00 0 
7ffa97616000-7ffa97619000 rw-p 00000000 00:00 0 
7ffa97619000-7ffa9761a000 r--p 00025000 08:01 25301405                   /lib/x86_64-linux-gnu/ld-2.23.so
7ffa9761a000-7ffa9761b000 rw-p 00026000 08:01 25301405                   /lib/x86_64-linux-gnu/ld-2.23.so
7ffa9761b000-7ffa9761c000 rw-p 00000000 00:00 0 
7fff870f0000-7fff87111000 rw-p 00000000 00:00 0                          [stack]
7fff871c3000-7fff871c5000 r--p 00000000 00:00 0                          [vvar]
7fff871c5000-7fff871c7000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
Аварийный останов (сделан дамп памяти)

With the 1st program, it only works with large numbers (about more than 70), and it also fails with small numbers.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Sergey Sakhno, 2017-08-21
@Conqueror3

https://code-live.ru/post/cpp-command-line-arguments/

A
awdemme, 2017-08-21
@awdemme

C 1 or 0 starts indexing the array of command line argument pointers

The null element usually stores the path to your program's executable file itself.
And starting from the 1st element - command line arguments.

R
Rsa97, 2017-08-21
@Rsa97

https://msdn.microsoft.com/en-us/library/88w63h9k.aspx
And the program crashes because you do not check the size of the allocated buffer before using the function

strcpy(char_ptr, "Thes is memory is located in the heap.");
If less than the length of your string +1 is allocated, then the rest of the string is written to an arbitrary location, causing an error.

D
Derevyanko Alexander, 2017-08-21
@dio4

use strncpy() so it's more reliable and more..
"If the string contains a valid sequence of digits representing the number 0, then 0 is also returned, and it is impossible to determine from the returned number whether the string contains a valid number or not. The newer strtol function does not have this disadvantage, so in cases where it is critical, it should be used.
replace your line
else
mem_size = atoi(argv[0]);
on else
mem_size = atoi(argv[1]);
so it doesn't crash (program name ./atoi)
output
[email protected]:~/tmp$ ./atoi 0123
[+] allocating 123 bytes of memory on the heap for char_ptr
char_ptr (0xbd3010) --> 'Thes is memory is located in the heap.'
[+] allocating 12 bytes of memory on the heap for Int_ptr
char_ptr (0xbd3010) --> 'new memory'
[-] freeing int_ptr's heap memory...
[-] freeing char_ptr's heap memory..
[email protected] :~/tmp$
Well, it works without parameters. Then the memory is 50 by default.
And it crashes if the memory is passed zero, then $ ./atoi 0
then the output is
*** Error in `./atoi': free(): invalid next size (fast): 0x0000000000973030 ***
Crash (memory dumped)
like this that also enter the check of the passed arguments into the code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question