memcpy在这个程序中做了什么?

3 c string malloc memcpy realloc

我正在编写一个程序,其中输入将从stdin中获取.第一个输入是一个整数,表示从stdin读取的字符串数.我只是逐个字符地读取字符串到动态分配的内存中,并在字符串结束后显示它.
但是当字符串大于分配的大小时,我使用realloc重新分配内存.但即使我使用memcpy,程序仍然有效.是不是使用memcpy的未定义行为?但是在C使用Realloc的示例不使用memcpy.那么哪一个是正确的方法呢?我的程序如下所示是正确的吗?

/* ss.c
 * Gets number of input strings to be read from the stdin and displays them.
 * Realloc dynamically allocated memory to get strings from stdin depending on
 * the string length.
 */

#include <stdio.h>
#include <stdlib.h>

int display_mem_alloc_error();

enum {
    CHUNK_SIZE = 31,
};

int display_mem_alloc_error() {
    fprintf(stderr, "\nError allocating memory");
    exit(1);
}

int main(int argc, char **argv) {
    int numStr;                  //number of input strings
    int curSize = CHUNK_SIZE;    //currently allocated chunk size
    int i = 0;                   //counter
    int len = 0;                 //length of the current string
    int c;                       //will contain a character
    char *str = NULL;            //will contain the input string
    char *str_cp = NULL;         //will point to str
    char *str_tmp = NULL;        //used for realloc

    str = malloc(sizeof(*str) * CHUNK_SIZE);
    if (str == NULL) {
        display_mem_alloc_error();
    }    
    str_cp = str;   //store the reference to the allocated memory

    scanf("%d\n", &numStr);   //get the number of input strings
    while (i != numStr) {
        if (i >= 1) {   //reset
            str = str_cp;
            len = 0;
        }
        c = getchar();
        while (c != '\n' && c != '\r') {
            *str = (char *) c;
            printf("\nlen: %d -> *str: %c", len, *str);
            str = str + 1;
            len = len + 1;
            *str = '\0';
            c = getchar();
            if (curSize/len == 1) {
                curSize = curSize + CHUNK_SIZE;
                str_tmp = realloc(str_cp, sizeof(*str_cp) * curSize);
                if (str_tmp == NULL) {
                    display_mem_alloc_error();
                }
                memcpy(str_tmp, str_cp, curSize);    // NB: seems to work without memcpy
                printf("\nstr_tmp: %d", str_tmp);
                printf("\nstr: %d", str);
                printf("\nstr_cp: %d\n", str_cp);
            }
        }
        i = i + 1;
        printf("\nEntered string: %s\n", str_cp);
    }
    return 0;
}

/* -----------------
//input-output
gcc -o ss ss.c
./ss < in.txt

// in.txt
1
abcdefghijklmnopqrstuvwxyzabcdefghij

// output
// [..snip..]
Entered string:
abcdefghijklmnopqrstuvwxyzabcdefghij
-------------------- */
Run Code Online (Sandbox Code Playgroud)

谢谢.

sim*_*onc 7

你的程序不太正确.您需要删除呼叫以memcpy避免偶尔的,难以诊断的错误.

realloc手册页

realloc()函数将ptr指向的内存块的大小更改为size字节.内容将在从区域开始到新旧尺寸的最小范围内保持不变

所以,你不需要调用memcpyrealloc.实际上,这样做是错误的,因为您之前的堆单元可能已在realloc调用中释放.如果它被释放,它现在指向具有不可预测内容的内存.