I'm probably missing something obvious, but my C is pretty rusty and I'm not having any luck making sense of this. I have a loop where I want to iterate over an array of uint64_t values coming from libdvdnav and then format the values and insert them into a string.
The header for libdvdnav defines the function I'm calling thusly:
uint32_t dvdnav_describe_title_chapters(dvdnav_t *self, int32_t title, uint64_t **times, uint64_t *duration);
Here's how I'm defining the variables used and executing the call (dvdnav and args[0] are defined and initialized elsewhere):
uint64_t *times;
uint64_t duration;
uint32_t times_array_len;
times_array_len = dvdnav_describe_title_chapters(dvdnav, atoi(args[0]), ×, &duration);
The code below seems to work, and compiles & runs w/o error, but of course only the first value in the array is inserted:
int i = 0;
uint64_t a_time = times[0];
while(i < times_array_len){
char time_json[100];
sprintf(time_json, "{\"chapter\":\"%d\",\"time\":\"%u\"},", i, a_time);
strcat(payload, time_json);
i++;
}
If I modify this to select each value in the array it still compiles clean, but throws a segfault at runtime:
int i = 0;
while(i < times_array_len){
char time_json[100];
sprintf(time_json, "{\"chapter\":\"%d\",\"time\":\"%u\"},", i, times[i]);
strcat(payload, time_json);
i++;
}
I thought maybe there was something in one of the array elements that was a problem (a too-large value, unexpected, NULL, etc.) but even if I replace the variable i with a known-reasonable element (say, 0) it still segfaults.
I'm sure there's countless other improvements to be made here (safer allocations, overflow protection, etc.) but the part I'm struggling to decipher is getting those values out of the array an into my formatted string.
strcat()call looks scary ...times_array_len, andtimesis smaller then it is. Second your payload too short for save all this data.payloadbuffer and got it to work; seems like I had done that before but perhaps not enough. I do want to make sure that's not just masking other problems though so I'm going to poke at it a bit before considering it fixed :)