anon349 anon349 -4 years ago 79
C Question

Dynamically allocated string from command line argument

I'm looking to process a string passed via a command line argument with a for loop in C. I'm wondering if this would be the correct way.

main(int argc, char * argv[])
{
char * somestring;
somestring = malloc( (strlen(argv[1]) + 1) * sizeof(char) );
somestring = argv[1];

...
}


or would C allocate the appropriate memory if I did:

char * somestring;
somestring = argv[1];

Answer Source

If you want to copy an argument in your own allocated memory then you have to write

int main(int argc, char * argv[1])
{
    char * somestring;
    somestring = malloc( strlen( argv[1] ) + 1 );
    strcpy( somestring, argv[1] );

       ...
}

otherwise statement

    somestring = argv[1];

results in a memory leak.

Also do not forget to free the memory when it will not be needed any more.

Take into account that though this record

int main(int argc, char * argv[1])

is valid it is better to write

int main(int argc, char * argv[])

because your intention by specifying char * argv[1] is not clear

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download