Question

I have a structure where I stored some values as shown below:

struct cmd { 
    char *pname;
    char *pdesc;
}; 

Following initialization I made as:

struct cmd[] = {{"show", "show items"},
                {"exit", "exit the shell"},
                {"setitem",   "setting item"}
               };    

I'm using sprinf() to print by storing all the pname ans pdesc as below,

int length = 0;    
char *resultcmd;    
for (indx = 0; indx< cmdCount; indx++) {
     length += sprintf(resultcmd+length, cmd[indx].pname, cmd[indx].pdesc);    
}    

Please help me how to allocate memory for resultcmd, It worked when i make resulecmd as array of some length, but if more pname and pdesc are added buffer overruns. Please help me.

Was it helpful?

Solution

If you want safely output data to buffer resultcmd you have to find out its length before and use it:

size_t length = 1; // 1 symbol needed to store \0', 
                   // because strlen() returns length 
                   // without NULL-termination symbol
// compute length:
for (intx = 0; indx < cmdCount; indx++) {
     length += strlen(cmd[indx].pname) + strlen(cmd[indx].pdesc);
}

char *resultcmd = malloc(length);
int written = 0, ret = 0;

// print cmds to C string
for (indx = 0; indx < cmdCount; indx++) {
     ret = snprintf (resultcmd + written, length - written, 
                     "%s%s", cmd[indx].pname, cmd[indx].pdesc))
     if (0 > ret) {
         fprintf (stderr, "snprintf() error: %s\n", strerror(errno));
         break;
     } else {
         written += ret;
     }
}
/* 
 * some useful code here
 */
free(resultcmd);

OTHER TIPS

You can use snprintf(char *dest, size_t maxlen, char *fmt, ...) to bound the size of your print. If the function fails, it returns the number of characters that would have been written, had there been enough space; so that +1 is what you need to realloc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top