char *allocate_string(size_t size) {
char *str = malloc(size);
if (str == NULL) {
return NULL; // let the caller handle the error
}
return str;
}
int some_function(char *ptr) {
if (ptr == NULL) {
return -1; // error code
}
// do work
return 0; // success
}
void some_function(char *ptr) {
if (ptr == NULL) {
// Maybe print error or just return silently
return;
}
// do stuff
}
in main
int main() {
char *str = malloc(100);
if (str == NULL) {
perror("malloc failed");
return 1; // return non-zero to indicate failure
}
// ...
free(str);
return 0;
}
risky crashing
if (str == NULL) {
perror("malloc failed");
exit(EXIT_FAILURE); // from stdlib.h
}
function pointer
void hello(const char *name) {
printf("Hello, %s!\n", name);
}
void call_with_name(void (*func)(const char *), const char *name) {
func(name); // Call the function with the name
}
int main() {
call_with_name(hello, "Alice"); // ✅ OK
call_with_name(&hello, "Bob"); // ✅ Also OK
}
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Top comments (0)