0

I'm trying to use strcpy_s, but i get another error dealing with the size, saying : L "Buffer is too small && 0" when i try to run the program, and i dont know ifsizeof tochar from strcpy_s(tochar, sizeof tochar, test.c_str()); is correct because I keep getting this error.

Full compiling code:

    #include "stdafx.h"
    #include <string>
    #include <string.h>
    #include <cstring>
    #include <stdlib.h>
    #include <errno.h>
    #include "stdafx.h"
    #include <iostream>
    #include <string>
    #include <fstream>
    #include <vector>
    #include <sstream>  
    #include <iomanip>
    #include <stdio.h>
    using namespace std;
    using std::vector;
    using std::string;

    int main()
    {


        std::string test;
        std::vector<std::string> v3 = { "filename1", "filename2","filename3", };
        for (int m = 0; m < v3.size(); m++) {
        test = "\"" + v3[m] + ".txt" + "\"";
            char * tochar = new char[test.length() + 1];
            strcpy_s(tochar, sizeof tochar, test.c_str());
            std::cout << tochar << std::endl;

        }
return 0;
    }

I cant use strcpy in c++ 2015, i have to use strcpy_s now because strcpy gives a different error, and i dont want to just turn off the error. (unless there is some sort of code i can put in the program that will let it compile with strcpy)

I want the tochar to output: "filename1.txt"

donnie
  • 17
  • 1
  • 7

3 Answers3

1

The second copy to strcpy_s should be the number of characters you wish to copy.

strcpy_s(tochar, test.length() + 1, test.c_str());

would be one way to write it, I think.

sizeof tochar

is giving you the size of the char pointer variable, not the size of the array you've allocated.

Evan VanderZee
  • 797
  • 6
  • 10
1

Instead of this strcpy_s(tochar, sizeof tochar, test.c_str()); you need to do strcpy_s(tochar, test.length() + 1, test.c_str());

When you say sizeof tochar, you are having value 4 or 8 as it is an pointer. But for the api, you need to tell the size of destination array

Ritesh
  • 1,809
  • 1
  • 14
  • 16
0

to use strcpy try dont use

#include <stdio.h>

use

#include <cstdio>
I will try
  • 41
  • 1
  • 6