Getting segmentation failure in Realloc

Here I want to create dynamic memory. here i dnt know the size of the output and i want to print the last final result after the 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);

}
+5
source share
3 answers

There are two main problems:

  • 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()- this is the wrong way to find out the size resultsand buffer. It will just return the size of the pointer. For resultsyou probably want to track the selected size yourself. For bufferyou are probably looking strlen().

Once you fix this, you need to make sure it resultsends as a zero-terminated string. This is necessary for proper operation printf().

+11
source

, -, " , ". , , , , .

API: , .

realloc(), ? , .

, :

  • (, ),
  • , , ( , )

n , , . , , , () .

+2

realloc (results, sizeof (results) + sizeof (buffer));

.

  • realloc() , , , , ; , :

    ptr = realloc (ptr, newSize);

  • sizeof() . sizeof(results) sizeof(buffer) 8. :

    results = realloc (, ctr * 514);
    ctr short, 0 while .

  • 514, , :

    char buffer [514];

    Regards

+1
source

All Articles