I've still getting an error of how the stack around newRow
is tried using strncat()
so that I can say how many new charters that where added to the string, but in the end I still have a corruption around newRow
.
In terms of a variables being passed into this function, I think they are pretty straight forward. I also use sizeOfString
as a custom made function because I'm not allowed to use the standard sizeof
function.
char* makeRow(char elementOne[20], int elementNumber, int numCycles, int orginalData[40], float ctValues[7]){
char newRow[] = "";
int lookingAt;
int dataPoint;
char* elementPtr;
int charArrSize;
elementNumber = elementNumber--;
elementPtr = elementOne;
int lenOfElemnt = *(&elementOne + 1) - elementOne;
//charArrSize = sizeOfString(elementPtr);
charArrSize = sizeOfString(elementOne);
strncat(newRow, elementOne, charArrSize);
//strcpy(csvThirdRow, (",%s", elementOne));
for (int i = 1; i <= 5; i++)
{
lookingAt = (((i - 1) * 5) + 1 - 1);
int maxLookingAt = numCycles * 5;
dataPoint = orginalData[lookingAt];
char dataPointBuffer[100];
if (lookingAt < maxLookingAt)
{
sprintf(dataPointBuffer, ",%d", dataPoint);
charArrSize = sizeOfString(dataPointBuffer);
strncat(newRow, dataPointBuffer, charArrSize);
}
else
{
strncat(newRow, ",",1);
}
}
char ctBuffer[20];
float ctNumber = ctValues[elementNumber];
sprintf(ctBuffer, ",%.2f\n", ctNumber);
charArrSize = sizeOfString(ctBuffer);
strncat(newRow, ctBuffer, charArrSize);
return newRow;
}
If we omit the array dimension, compiler computes it for us based on the size of initialiser.
So, this
char newRow[] = "";
is same as this
char newRow[1] = "";
The size of newRow
array is 1
.
You are trying to copy more than 1
character to newRow
array which is leading to undefined behaviour and resulting in corruption.
From strncat() :
The behavior is undefined if the destination array does not have enough space for the contents of both dest and the first count characters of src, plus the terminating null character....
May you should try giving enough size to newRow
array, like this
char newRow[1024] = {0};
There is another problem in your code -
You are returning the newRow
from makeRow()
function. newRow
is local variable of makeRow()
function. Note that a local(automatic) non-static variable lifetime is limited to its scope ie the block in which it has been declared. Any attempt to access it outside of its lifetime lead to undefined behaviour.
Couple of things that you can do to fix it:
Either make numRow
array static
or declare numRow
as char *
type and allocate memory dynamically to it and, in this case, make sure to free
it once done with it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.