If I am reading a C string such as:
char myData[100];
and I want to process this data and produce a copy out of it, so my code looks like:
char myData[100], processedData[50];
loop
fill myData from file...
setProcessedData(myData, processedData);
store processedData to file...
where setProcessedData is a function that returns a processed string. let’s say for simplicity it returns a substring
void setProcessedData (char *myData, char *processedData) {
memCopy( processedData, myData, 5);
}
Is what I am doing something wrong? Like creating extra objects/strings? is there a better way to do it?
Let’s say I read string from file which contains *
I am* A T*est String* But Ho*w to Process*.
I want to get substring which has the first 3 s. So my processedData
I am A t*est String*
and I want to do this for all lines of a file as efficient as possible.
Thanks
Problem is that your function is inherently unsafe, this because you make assumption about the allocated memory by parameters you pass to the function.
If someone is going to call
setProcessedDataby passing a string which is shorter than 5 bytes then bad things will happen.In addition you are copying memory with
memcpyby using a raw dimension, a safer approach, even if it is quite picky in this situation, is to usesizeof(char)*5.Best thing you can do, though, is to follow the same approach used by safer functions of standard library like
strcpyvsstrncpy: you pass a third parameter which is the maximum length that should be copied, eg: