Question

I hope you can help me out with this. I have an array of char pointers which I want to hold unique strings. I have a method which returns a char pointer and I am setting the return value of this function to incrementing values in the array:

// array to hold strings    
char * finalStack[STR_LEN] = {""};

// returns char * to store in array
char * generateStackFrame (char stackVals[]) {
   static char buffer[BUF_LEN];
   int index = 0;
   // 8 bytes
   if (stackVals[0] == stackVals[1] == stackVals[2] == stackVals[3]) {
       snprintf (buffer, sizeof(buffer), "|       %c       |", stackVals[0]);
   // 4 bytes + padding
   } else {
       for (index = 0; index < 4; index++) {
           if (stackVals[index] == '\0')
               stackVals[index] = 'X';
       }
       snprintf (buffer, sizeof(buffer), "| %c | %c | %c | %c |",
                 stackVals[3], stackVals[2], stackVals[1], stackVals[0]);
   }
   return buffer;
}

The method is called like this:

...
    finalStack[index] =  generateStackFrame (stackVals);
...

I have a loop which generates different values, then calls the method and sets the result to an index in the char * array. This works for the first value, but for each sequential value, even though I am setting the new char * to the next position in the array, it sets all of the values in the array to the current string. I'm guessing this is an obvious mistake, maybe I'm not fully understanding the concepts going on here.

Thanks for any help!

Was it helpful?

Solution

You are using static char buffer[BUF_LEN]; in your function. The keyword static ensures that same space will be utilized in each function call. So when you sequentially set the values outside the function, they will end up pointing to the same space. Basically all indexes in array will be pointing to same string at the end.

To solve this, allocate new memory each time

char * generateStackFrame (char stackVals[]) {
    char* buffer;
    buffer = malloc(sizeof(char)*BUF_LEN);
    ///rest of code

   return buffer;
}

Note- dont use stack variable since it will be lost after returning from function call, allocate memory on heap using malloc

char * generateStackFrame (char stackVals[]) {
    char buffer[BUF_LEN];  //this is wrong

OTHER TIPS

As the code is currently written, every entry in finalStack will be a pointer to the same buffer that generateStackFrame uses every time that it's called.

To fix the problem, you need to malloc a new buffer in generateStackFrame, and then fill and return that buffer.

Side note: at some point in your program, you should free all of the buffers.

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