Memory allocation and **argv argument [closed]
Asked Answered
P

1

8

I know for what we use this argument, and I even know how to work with the argument.

There is only one things I still do not understand. How a program allocate memory for strings which came from the input. **argv has no allocated memory at the start of the program, isn't it? I was expecting segfault, but it didn't happen.

Does anybody know how this memory allocation work?

Prodigy answered 15/9, 2014 at 14:22 Comment(4)
the what what? huh?Supplicant
What do you mean by "has no allocated memory"? The pointers in argv are all valid and point to memory that's safe to access. What code did you expect to produce a segfault?Leptorrhine
It's allocated by the runtime library before main() is called.Swithin
possible duplicate?? #4196701Montparnasse
L
12

The C/C++ runtime processes the command line arguments and creates an area of memory where the arguments are put. It then calls your main() providing you a count of the number of arguments along with a pointer to the area where the arguments are stored.

So the C/C++ runtime owns the memory area allocated and it is up to the C/C++ runtime to deallocate the area once your main() returns or if some other C/C++ function is used to stop the program such as exit().

This procedure originated with the use of C under Unix and was kept for C++ as a part of providing the degree of backwards compatibility the C++ committee has tried to maintain.

Normally when your program loads, the entry point that is started by the loader is not your main() function but rather an entry point defined in the C/C++ runtime. The C/C++ runtime does various kinds of initialization to setup the environment that the C/C++ standards say will exist at the point when the main() function is called by the C/C++ runtime once the initialization is completed.

One of the steps during this initialization is the parsing of command line arguments provided which are then provided to the main() function as its function arguments.

Lamella answered 15/9, 2014 at 14:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.