Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Segmentation Fault in Realloc

Tags:

c

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);

}
like image 916
user1089679 Avatar asked Jan 30 '12 15:01

user1089679


1 Answers

There are two main issues:

  1. realloc() returns the new address:

    new_results = realloc(results, ...);
    if (new_results != NULL) {
      results = new_results;
    } else {
      /* handle reallocation failure, `results' is still valid */
    }
    
  2. 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.

like image 178
NPE Avatar answered Sep 28 '22 12:09

NPE