Home > OS >  little question about a thing when it comes to dynamically allocate a string, how can I solve?
little question about a thing when it comes to dynamically allocate a string, how can I solve?

Time:02-14

(this question is all about theory).

quick doubt, I don't know what to do: I need to do a malloc to store a string of its length plus 1 zero-terminator. Therefore I have to write: char* str = malloc(length 1), and in order to avoid buffer overflow/buffer overrun, I've thought about this solution:

int sum = length   1; 
if (sum > char storage limit) {
exit(1); 
} else {
char* str = malloc(length   1); 
NULL POINTER EXCEPTION CHECK.
}

okay, this could work, but I don't know what should I write instead of "char storage size".

knowing that char value range is -128<char<255, and char storage size is 1 byte, but I can't write 8, because 8 doesn't stand for 8 bits; how can I do it?

EDIT: perhaps, I can use sizeof operator this way: sizeof(char). And the code would become:

int sum = length   1; 
if (sum > sizeof(char)) {
exit(1);
} else { /* same way */ }

but because this kind of integer types are machine-dependent, their sotrage size may vary, therefore I think I should write int8_t, because stdint functions have always the same storage size. what do you think?

CodePudding user response:

You incorrectly understand the compiler message.

Firstly there is a compilation error

if (sum > )
         ^^^

and the compiler points to it.

Secondly the message means that instead of the type int of the variable length you should use the type size_t.

This message has nothing common with the buffer overflow. It means that the expression length 1 can result in integer overflow.

Pay attention to that sizeof( char ), sizeof( signed char ) and sizeof( unsigned char ) are always equal to 1.

  • Related