Home > Back-end >  How can I return a calloc pointer from C into C ?
How can I return a calloc pointer from C into C ?

Time:02-24

I am working on a personal project that requires me to call C functions from C code. These C functions return a calloc() pointer.

1t5.h

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

char * prob1(char * number);

1t5.c

#include <1t5.h>

char * prob1(char * number) {
    int ni = atoi(number);
    char prompt[] = "hello\n";
    char * answer = (char*)calloc(ni, sizeof(prompt));
    for (int i = 0; i < ni; i  ) {
        strcat(*answer, prompt);
    }
    return answer;
}

That C code is supposed to return a given number of "hello\n".

linking.cpp

string Link::problemRouting(string problem, vector<string> contents) {
    string answers = "";
    char * ca;

    int pi = stoi(problem);

    for (int i = 0; i < contents.size(); i  ) {
        ca = cv.stringToChar(contents[i]);
        // C Standard
        if (pi <= 5) {
            char * answer;
            switch(pi) {
                case 1:{
                    answer = prob1(ca);
                }
                case 2: {
                    answer = prob2(ca);
                }
                case 3: {
                    answer = prob3(ca);
                }
                case 4: {
                    answer = prob4(ca);
                }
                case 5: {
                    answer = prob5(ca);
                }
            }

            cout << answer;
            answers =answer;
            free(answer);
        }
    }

    return answers;
}

This C code takes the return value and saves it to store into a text file later.

The problem is when I input a number, lets say 257, then the return value is 257, and not a ton of "hello\n".

CodePudding user response:

Thanks to @Remy Lebeau for the answer.

My code contained many chances for memory to leak, resulting in a mess of a return value.

string Link::problemRouting(string problem, vector<string> contents) {
string answers = "";
char * ca;

int pi = stoi(problem);

for (int i = 0; i < contents.size(); i  ) {
    ca = cv.stringToChar(contents[i]);
    // C Standard
    if (pi <= 5) {
        char * answer;
        switch(pi) {
            case 1:{
                answer = prob1(ca);
                break;
            }
        }
        free(ca);
        cout << answer;
        answers =answer;
        free(answer);
    }
}

return answers;
}
  • Related