简体   繁体   English

memcpy,分段错误

[英]memcpy, segmentation fault

i have try to write this code, but i have found a problem with segmentation fault with memcpy ( i have try to see the code with debug) 我已经尝试编写此代码,但是我发现memcpy存在分段错误的问题(我已经尝试通过调试来查看代码)

        FILE *tp;
        int l = 0;
        while ((fgets(buffer, sizeof buffer, tp))) {
            // search equal sign
            char *equalsign = strchr(buffer, '=');
            l++;
            // search quote near value
            char *q1 = equalsign + 1;
            char *q2 = strchr(q1 + 1, '"');
            // extract name and value
            char* names = strndup(buffer, equalsign - buffer);
            char* values = strndup(q1 + 1, q2 - q1 - 1);
            memcpy(g_names,names,strlen(names));
            memcpy(g_values,values,strlen(values));
            free(names);
            free(values);
            }

with

const char* g_names[SIZE] = { 0, };
char* g_values[SIZE] = { 0, };
char buffer[MAXLINE] = {0,};

define as global. 定义为全局。 with the debug i have see that the problem is with memcpy (segmentation fault). 通过调试,我已经看到问题出在memcpy(分段错误)上。 anyone have a suggest? 有人有建议吗? Thanks. 谢谢。 Regards. 问候。

There are at least two problems with your code: First, it is using g_names as the destination of memcpy , which copies the characters over the array of pointers. 您的代码至少存在两个问题:首先,它将g_names用作memcpy的目标,该目标将字符复制到指针数组上。 You should be copying to g_names[l] (assuming l was to be the index in the g_names array). 您应该复制到g_names[l] (假设lg_names数组中的索引)。

Second, your code is missing the actual allocation of g_names[l] , something like: 其次,您的代码缺少g_names[l]的实际分配,例如:

g_names[l] = malloc(strlen(names) + 1);

But since you're calling strndup anyway, you can simply store the result of that call into the array: 但是由于无论如何都调用strndup ,因此您可以简单地将该调用的结果存储到数组中:

        // search for equal sign
        char *equalsign = strchr(buffer, '=');
        // search quote near value
        char *q1 = equalsign + 1;
        char *q2 = strchr(q1 + 1, '"');
        // extract name and value
        g_names[l] = strndup(buffer, equalsign - buffer);
        g_values[l] = strndup(q1 + 1, q2 - q1 - 1);
        l++;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM