简体   繁体   中英

Char pointer to read argv? Memory leak?

So my program is running and i also have no warnings from the compiler.

Right now, i simply use a char *name pointer to read in the argv[4] value.

I use this value then as an argument in a function, like so:

char *name = argv[4];
if (name != NULL)
   FunctionX(sl, rl, name, list1);

is there anything wrong with that approach, memory leak wise? If so, how should i change it?

I ask, because my compiler shows me no warnings or errors and everything works fine. When i run: gcc -o programm -fsanitize=address *.c or gcc -o programm -fsanitize=address *.c -Wall it compiles just fine. I had warnings before, but i fixed them. However, someone who reviewed my program said that they get a memory leak warning when using gcc -o programm -fsanitize=address *.c, altough i get no errors at all. Any ideas what could cause that?

This snippet doesn't leak memory. To do that, you'd need to call malloc , calloc or some other function that allocates memory, and then not call free . Simply shuffling pointers around doesn't cause leaks.

The only potential problem in this snippet is accessing argv out of bounds, if you don't check argc before.

is there anything wrong with that approach, memory leak wise? If so, how should i change it?

To have a memory leak, you first need to call malloc() . And you haven't.

I see no problem in the code you show. argv[] is just an array of pointers to strings already allocated for you in the C runtime. You need to consider it read only, as you can run in serious trouble if you modify any of the strings, or the array of pointers (it is normally implemented allocating the space for it in the stack, previous to call main() , so you had better not to touch it)

But for your question to be a good question, you need to show a complete example, the output you expect and the actual output you get, with a full, complete and ready to compile program (see How to create a Minimal, Reproducible Example ), and you have only post a snippet. I can only say that I don't see anything wrong in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM