在Realloc中获取分段错误

use*_*679 5 c

在这里,我想创建动态内存.在这里我不知道输出大小,我想在while循环后打印最后的最终输出.

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

}
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 11

有两个主要问题:

  1. realloc() 返回新地址:

    new_results = realloc(results, ...);
    if (new_results != NULL) {
      results = new_results;
    } else {
      /* handle reallocation failure, `results' is still valid */
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. sizeof()不是找出results和的大小的正确方法buffer.它只会返回指针的大小.因为results,您可能希望自己跟踪分配的大小.因为buffer,你可能正在寻找strlen().

修复上述内容后,您需要确保results最终为有效的NUL终止字符串.这对于printf()正常工作是必要的.

  • ...如果分配失败,则为"NULL". (2认同)