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:sizeof()is not the right way to find out the size ofresultsand ofbuffer. It would simply return the size of the pointer. Forresults, you probably want to keep track of the allocated size yourself. Forbuffer, you’re probably looking forstrlen().Once you fix the above, you need to make sure that
resultsends up as a valid NUL-terminated string. This is necessary for theprintf()to work correctly.