C question argv using Unix

Asked 2 years ago, Updated 2 years ago, 355 views

I'll make a.out using gcc For example, if you enter a.out 10 xyz, After dynamically assigning 10, you want to save the xyz value in argv. After the print is over, if you do the free style, munmap_chunk(): invalid pointer Aborted (core dumped) An error occurs. Why?

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

int main(int argc, char *argv[])
{
        if (argc >= 3)
        {
                int n;
                n = atoi(argv[1]);
                char *ptr = (char *)malloc(sizeof(char) * n);
                ptr = *(argv+2);
                printf("Size = %d\n", n);
                printf("Data = %s\n", ptr);
                free(ptr);
        }

        else
        {
                printf("argument errors\n");
        }
}

unix c linux

2022-11-16 17:52

2 Answers

When you assign a value to the ptr pointer, the address value stored in the ptr will change if it is not used in the form of *ptr=


2022-11-16 17:59

The C language string is the starting address of the char array. = Operators do not copy strings; they simply copy other address values.

What you actually have to do is you have to turn the for loop and put it all in one letter at a time, or you have to copy it using the strcpy function in string.h.

ptr = *(argv + 2);

You can modify the code above as below.

strcpy(ptr, argv[2]);

Additionally, #include <string.h> should be added at the top.


2022-11-16 20:03

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.