Hi,
I want to prase the options twice but no luck. It seg fault at free. See the code attached.
Hi,
I want to prase the options twice but no luck. It seg fault at free. See the code attached.
The address in the pointer is invalid. Debug and check where it goes illegal.
Making error is human, but for messing things thoroughly it takes a computer
Hi
in the code you post, the pointers didn't point to a memory allocated from the heap, they point to a memory in your 'data' or 'code' segment, depending on the compiling options you've used at compile time. so...
>>> free(parse_argv[i]);
when you try to free them - it chashes ...
just avoid freeing memory which you didn't allocate it previously.
how to allocate memory from the heap for parse_argv?
> // why segmentation fault in free?
There is no need to call free, because you haven't called malloc.
> // why second parse has no result?
Not sure - but as far as getopt is concerned, the array of pointers is the same. Maybe getopt has some internal state which causes it to remember where it got to the last time it was called.
You would need to read the manual page to find out how to reset this.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Yes, yes and yes. getopt has an integer (optind) which remembers how many times it has parsed. getopt is designed to parse command line argument and optind =0 at start. So I have to reset optind to 0 every time I parse. It's seg fault and I thought this is a memory problem in other places!Originally posted by Salem
> // why segmentation fault in free?
There is no need to call free, because you haven't called malloc.
I see...
> // why second parse has no result?
Not sure - but as far as getopt is concerned, the array of pointers is the same. Maybe getopt has some internal state which causes it to remember where it got to the last time it was called.
You would need to read the manual page to find out how to reset this.
Thank you for helping me.