Strcpy () corrupts copied string in Solaris but not Linux

I am writing C code for a class. This class requires our code to compile and run on the school server, which is a machine with a solarium. I am running Linux x64.

I have this line for parsing (THIS IS NOT ACTUAL CODE, BUT ENTERING MY PROGRAM):

while ( cond1 ){ 

I need to write "while" and "cond1" on separate lines. I used strtok()for this. On Linux, the following lines:

char *cond = NULL;
cond = (char *)malloc(sizeof(char));
memset(cond, 0, sizeof(char));
strcpy(cond, strtok(NULL, ": \t\(){")); //already got the "while" out of the line

will fix the string "cond1" correctly. However, this on a Solaris machine gives me the string "cone1".

Please note that in many other cases in my program the lines are copied correctly. (For example, "while") was committed correctly.

Does anyone know what is going on here?

+3
3

:

cond = (char *)malloc(sizeof(char));

char , - strcpy , strtok.

, , , malloc (, 16 ) , , , . , , - undefined.

, undefined , , .

strtok, .

- , , strtok. , ( , , , strtok ).

- ( instr - ):

cond = (char*)malloc(strlen(instr)+1);

, , instr, cond.

, sizeof(char) , .

+11

cond . strcpy . , .

, char *cond = malloc (1000); , .

+2

You only allocated memory for 1 character, but you are trying to save at least 6 characters (you need a place to complete \ 0). A quick and dirty way to solve it is to just say

char cond [128]

instead of malloc.

+1
source

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


All Articles