c - 重新分配 : Segmentation fault

标签 c memory memory-management

取下面的代码,在a.c中:

struct header {
    char **name;
};
int main(void)
{
    int i=0;
    char **p;
    struct header h;
    char tmp[10];
    memset(&h, 0, sizeof(h));

    for(i=1;i<10;i++){
        sprintf(tmp, "name%d", i); 
        p = realloc(h.name, sizeof(char*)*i);
        printf("h->name=%p, p=%p\n", h.name, p); 
        h.name = p;
        h.name[i-1] = malloc(100);
        strncpy(h.name+i-1, tmp, strlen(tmp));
        printf("h->name=%s\n", h.name+i-1);
    }   
    return 0;
}

在我 gcc a.c./a.out 之后,发生以下错误: 段错误 我对此一无所知,到底发生了什么?

编辑1: 找到问题了! strncpy(h.name+i-1, tmp, strlen(tmp)) 应该 strncpy(h.name[i - 1], tmp, strlen(tmp) + 1) 并且这个问题可以通过 gcc warnings:/usr/include/string.h:131:14: note: expected 'char * __restrict__' but argument is of type 'char **' 找到,真傻!感谢大家!

最佳答案

strncpy(h.name+i-1, tmp, strlen(tmp)); 不会以 null 终止目标字符串。可能是下一个 printf() 试图打印它时崩溃了。

关于c - 重新分配 : Segmentation fault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16975187/

相关文章:

c - 使用指向数组的 void 指针来乘以矩阵

c++ - 在 Linux 上使用 C/C++ 中的 write() 函数通过 UART Beaglebone Black 写入 70kB

c - Linux串口编程,ttyS0

c - 在文本框和程序源代码之间传递信息

java - 为 lambda 表达式存储 out 范围变量的位置

c# - .NET中的内存管理

iphone - 仪器中可接受的实时字节值是多少?

objective-c - 对 Objective-C 的指针内存管理的误解

c++ - 如何强制库使用自定义 std::allocator?

ios - 从数据库存储和检索图像时的内存问题