I have this exercise: "create a function in order to subtract two strings".
my attempt works just fine (with the help of an old answer here on stack overflow). The problem is that when I debug, the debugger doesn't warn me on anything, but I have a grey squiggle below the argument of malloc. visual studio says that "a sub-expression may overflow before being assigned to a wider type". This is my thought: "I need to write an if-check before malloc to make sure the sub-expression won't overflow. To do it, I've thought to do this way: int sum = length 1; if (condition), then do this (allocation)." the problem is that I don't know the condition to be checked. based on an old discussion here on stack overflow, I know that if I have a subtraction I have to do this way
int c = a - b;
if (c >= a) {
// do allocation;
} else {
return NULL;
}
but it works only for subtraction, but if I have an addition this method fails. therefore, this method doesn't work.
how can I do it?
#include <stdlib.h>
#include <stdio.h>
#
char* subtract(const char* a, const char* b) {
int a_1 = atoi(a); int b_1 = atoi(b); int result = 0;
result = a_1 - b_1;
int length = snprintf(NULL, 0, "%d", result);
char* str = malloc(length 1);
if (str == NULL) {
return NULL;
}
snprintf(str, length 1, "%d", result);
return str;
}
int main(void) {
char a[] = "4567";
char b[] = "568";
char* c;
c = subtract(a, b);
return 0;
}
CodePudding user response:
but I have a little warning. it's located in the argument of malloc, as I said.
malloc(length 1);
length
is signed integer and it can overflow if you add 1 to it.
Solution:
cast it to size_t
malloc((size_t)length 1);
BTW What is the difference between "little" and "big" warnings?
PS How to substract "4564536456645645645"
and "545643563456436565436"
using your solution?