c - 使用 strncpy。 Valgrind 抛出无效读取

标签 c malloc valgrind strncpy

我做了这个函数:

void procesar_llamadaAFuncion(t_proceso *unProceso, char *sentencia){
    char *nombreFuncion = sentencia;
    char *nombreFuncionSinParentesis = NULL;

    string_trim(&nombreFuncion);
    nombreFuncionSinParentesis = malloc(sizeof(char)*(strlen(nombreFuncion)-2));
    strncpy(nombreFuncionSinParentesis, nombreFuncion, strlen(nombreFuncion)-2);

    puts(nombreFuncionSinParentesis);

    push_stack(unProceso->pcb->seg_stack, nombreFuncionSinParentesis, unProceso->pcb->program_counter);

    unProceso->pcb->program_counter = get_pos_funcion(unProceso->pcb->funciones, nombreFuncionSinParentesis);

    free(nombreFuncion);
    free(nombreFuncionSinParentesis);

t_proceso 是什么并不重要,问题是这个函数接收一个字符数组。

函数将始终接收“something()”的字符数组,我想做的是删除最后两个字符“()”,然后调用函数 push_stack()。

问题是当我运行 Valgrind 时,我得到这个:

==17129== Invalid read of size 1
==17129==    at 0x4C2BFD4: __GI_strlen (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==17129==    by 0x50BFCEB: puts (ioputs.c:37)
==17129==    by 0x403D30: procesar_llamadaAFuncion (proceso.c:455)
==17129==    by 0x40313D: procesar_siguiente_instruccion (proceso.c:132)
==17129==    by 0x404B1A: probarProcesos (test.c:83)
==17129==    by 0x404C7F: main (test.c:111)
==17129==  Address 0x5436da8 is 0 bytes after a block of size 8 alloc'd
==17129==    at 0x4C2B6CD: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==17129==    by 0x403CDF: procesar_llamadaAFuncion (proceso.c:452)
==17129==    by 0x40313D: procesar_siguiente_instruccion (proceso.c:132)
==17129==    by 0x404B1A: probarProcesos (test.c:83)
==17129==    by 0x404C7F: main (test.c:111)

我不知道我做错了什么,所以任何帮助将不胜感激。

最佳答案

这是因为strncpy不以 null 终止目标字符串:

Copies the first num characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.

No null-character is implicitly appended at the end of destination if source is longer than num (thus, in this case, destination may not be a null terminated C string).

这应该可以解决问题:

size_t nobmreLen = strlen(nombreFuncion)-2;
// Don't forget to add +1 for the null terminator
nombreFuncionSinParentesis = malloc(sizeof(char)*(nobmreLen+1));
strncpy(nombreFuncionSinParentesis, nombreFuncion, nobmreLen);
nombreFuncionSinParentesis[nobmreLen] = '\0';

关于c - 使用 strncpy。 Valgrind 抛出无效读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13132051/

相关文章:

c - C 输出背后的逻辑

c - Valgrind malloc 泄漏

c++ - Valgrind显示的空闲空间大于分配空间

c - 无法理解为什么释放内存会引发错误

ios - NSMutableDictionary 有两个指向同一对象的键导致 "double free"异常

linux - malloc() 是根据单线程还是多线程执行不同的?

c++ - 了解 Valgrind 输出

c++ - ULARGE_INTEGER union 的意义何在?

c++ - 使用字符串 C,读写字符串

c - 仅为数组的一个元素分配内存