Malloc, strlen, strcat

Below is a snippet of code from the very beginning of the program that I am writing (which contains an error).

    char *name;
    char *name2;

    if (argn != 2) {
        printf("You have to enter the name of the input file");
        return 1;
    }

    name = malloc(strlen(arg[1]) + 1);      
    name2 = malloc(strlen(arg[1]) + 1);

    strcpy(name, arg[1]); 
    strcpy(name2, arg[1]);

    strcat(name2, "-results.pdb");  

There is an error here that, with strcat, really, is name2not large enough to perform the above operation. Still strcatperformed without problems. However, later in the completely unrelated part of the program, the operation with another array that was initialized after this strcatgives an error. This is an integer array for which I assign values ​​to its elements, and it gives an error before I can assign all values. I assume that since there is not enough memory in name2 to operate on it, it somehow affects the following initialized arrays. I would like to understand:

1- , , , , 2, , ?

2- , , , strcat. , memory problematic, ?

+4
3

strcat .

, . , . .

, undefined. , . , , , , . , malloc , .

-

name2 = malloc(strlen(arg[1]) + sizeof "-results.pdb");

"+1" NUL, sizeof "-results.pdb" 13.

asprintf ( ISO C, Unix), :

asprintf(&name2, "%s-results.psb", arg[1]);

! strlen, strcat, no sizeof, no malloc. "--", TM.

+10

strcat:

char *strcat(char *dest, const char *src);

strcat() src dest, ('\ 0') dest,         . , dest . dest        , , .

, " ", - .

, , strcat, , ( ), , , malloc, , , . , int char *dest, , .

strncat, , asprintf , , .

- :

char *newstr = NULL;
asprintf(&newstr, "%s%s", name2,"-results.pdb");

malloc ed, newstr, .

+5

malloc

name2 = malloc(strlen(arg[1])+100);

strcat, , ... , "undefined "...

Microsoft ++, : https://msdn.microsoft.com/en-us/library/e5ewb1h3%28v=vs.90%29.aspx

#ifdef _Windows
#include "stdlib.h"
#include "crtdbg.h"
#endif

, , :

_CrtSetDbgFlag 
_CrtSetBreakAlloc 

There should be a lot of good resources, and it's easier to use than it looks. See this link for more options:

GCC memory leak detection equivalent to Microsoft crtdbg.h?

-4
source

Source: https://habr.com/ru/post/1623079/


All Articles