Here i want to create dynamically memory. here i dnt know the output size and i want to print last final output after while loop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main() {
char *sdpCommand = "sdptool browse 04:18:0F:B1:48:B5";
FILE *fp;
fp = popen(sdpCommand, "r");
char *results = 0;
if (fp == NULL) {
printf("Failed to run command\n");
return;
}
char* buffer = malloc(514);
while (fgets(buffer, strlen(buffer) - 1, fp) != NULL) {
realloc(results, strlen(results) + strlen(buffer));
memcpy(results + strlen(results), buffer, strlen(buffer));
}
printf("Output ::: %s", results);
/* close */
pclose(fp);
sleep(1);
}
There are two main issues:
realloc() returns the new address:
new_results = realloc(results, ...);
if (new_results != NULL) {
results = new_results;
} else {
/* handle reallocation failure, `results' is still valid */
}
sizeof() is not the right way to find out the size of results and of buffer. It would simply return the size of the pointer. For results, you probably want to keep track of the allocated size yourself. For buffer, you're probably looking for strlen().
Once you fix the above, you need to make sure that results ends up as a valid NUL-terminated string. This is necessary for the printf() to work correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With