LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   strcat Core Dump (https://www.linuxquestions.org/questions/programming-9/strcat-core-dump-299128/)

monil 03-08-2005 08:34 AM

strcat Core Dump
 
I have used the sys function to get the pathname as follows...

Code:

#include <string.h>

int main()
{
char *cmd = "asas/sdfsdf/ghgf";
char *dir = "dirname ";

strcat(dir,cmd);
puts(dir);
//system(dir);
return 0;
}

What i need is "dirname asas/sdfsdf/ghgf"

I need to pass this to the system function (commented...)

Thank you.

-Monil

hk_linux 03-08-2005 08:51 AM

The memory for cmd and dir are allocated at compile time itself. You are tyring to copy another string into the same variable without allocating more memory. Thats why it is dumping.

Try allocating for cmd, dir and then reallocate for dir and proceed.

int main()
{
char *cmd;
char *dir;
int newsize;

cmd = (char *) calloc (20,1);
dir = (char *) calloc (20,1);

strcpy (cmd, "asas/sdfsdf/ghgf");
strcpy (dir, "dirname ");
newsize = strlen(cmd) + strlen(dir) +1; // 1 for NULL

dir = (char *) realloc (dir, newsize);
strcat(dir,cmd);
puts(dir);
//system(dir);
return 0;
}


HTH

hk_linux 03-08-2005 08:52 AM

Also check for the return status of calloc and realloc.

Hko 03-08-2005 11:15 AM

Quote:

Originally posted by hk_linux
Also check for the return status of calloc and realloc.
...also free() the memory when your program doesn't need the strings anymore.
e.g.:
Code:

int main()
{
    char *cmd;
    char *dir;
    int newsize;

    cmd = (char *) calloc (20,1);
    dir = (char *) calloc (20,1);

    strcpy (cmd, "asas/sdfsdf/ghgf");
    strcpy (dir, "dirname ");
    newsize = strlen(cmd) + strlen(dir) +1; // 1 for NULL

    dir = (char *) realloc (dir, newsize);
    strcat(dir,cmd);
    puts(dir);
    //system(dir);
    free(cmd);
    free(dir);

    return 0;
}


Hko 03-08-2005 11:20 AM

Or, easier:
Code:

#include <stdio.h>
#include <string.h>

#define MAXLEN 80

int main()
{
    char dir[MAXLEN];

    strcpy(dir, "dirname ");
    strcat(dir, "asas/sdfsdf/ghgf");
    puts(dir);
    //system(dir);
    return 0;
}



All times are GMT -5. The time now is 11:46 PM.