App keeps crashing with malloc issue objective c and c - objective-c

Question- I want to be able to run my c code over and over again however after the first execution of it in my objective c it crashes and I receive an error in xcode "Thread 1 EXC_BAD_ACESSS (code=1, address=0x0)". It's really strange because the first time I run it works then any time after that it dies on me. Any help would be greatly appreciated.
Here is my c code
funcc.c
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define BUFLEN 1024
#define MYFREE(x) free(x); x = NULL;
char const *ipcc;
char *statuss;
char *both_words;
char *s1;
char *s2;
char *results;
void concat()
{
**// THIS IS THE LINE I RECIEVE THE EXC_BAD_ACCESS ERROR/////************** results
results = malloc(strlen(s1)+strlen(s2)+1);
strcpy(results, s1);
strcat(results, s2);
both_words = results;
return;
}
char* P(const char *ipAddr)
{
int pipe_arr[2];
char buf[BUFLEN];
pipe(pipe_arr);
if(fork() == 0)
{
dup2(pipe_arr[1], STDOUT_FILENO);
execl("/sbin/ping", "ping", "-c 1", ipAddr, (char*)NULL);
}
else //parent
{
wait(NULL);
read(pipe_arr[0], buf, BUFLEN);
char *xxx = deblank(buf);
char *input = xxx;
char delimiter[] = " ";
char *i, *j, *remainder, *context;
int inputLength = strlen(input);
char *inputCopy = (char*) calloc(inputLength + 1, sizeof(char));
strncpy(inputCopy, input, inputLength);
i = strtok_r (NULL, delimiter, &context);
j = strtok_r (NULL, delimiter, &context);
remainder = context;
s1 = i;
s2 = j;
concat();
char *sx = search(both_words);
//getchar();
}
close(pipe_arr[0]);
close(pipe_arr[1]);
return both_words;
}
void ConnectionMain(){
char *val = P(ipcc);
printf("%s\n", val);
char *valb = "0packets";
if(strcmp(val, valb) == 0)
{
printf("%s\n", "noconnection");
statuss = "noconnection";
//free(concat);
//return "noconneciton";
}
else
{
printf("%s\n", "connected");
statuss = "connected";
//free(concat);
//return "connected";
}
s1 = NULL;
s2 = NULL;
results = NULL;
both_words = NULL;
ipcc = NULL;
}
funcc.h
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
extern const char *ipcc;
extern char *statuss;
//const char *TestConnection(const char *ip);
void ConnectionMain();
Here is my objective c code
ViewCtrl.m
- (void)checkconnection
{
ConnectionMain();
//const char *ipc = [ip UTF8String];
//TestConnection(ipc);
char *statuss1 = "noconnection";
NSString* xx = [NSString stringWithUTF8String:statuss];
//printf("%s\n", statuss);
if(strcmp(statuss, statuss1) == 0)
{
_ip_label.stringValue = #"No Connection";
//I TRIED SETTING THESE BACK TO NULL BUT STILL NO LUCK
// I ALSO TRIED FREE(CONCAT) STILL NO LUCK
ipcc = NULL;
statuss = NULL;
statuss1 = NULL;
}
else
{
//I TRIED SETTING THESE BACK TO NULL BUT STILL NO LUCK
// I ALSO TRIED FREE(CONCAT) STILL NO LUCK
_ip_label.stringValue = #"Connection Success";
ipcc = NULL;
statuss = NULL;
statuss1 = NULL;
}
}
- (IBAction)ipButtonClicked:(id)sender {
//THIS IS WHERE I EXECUTE MY C CODE///////*********
NSString *ip_text = _ip_text_box.stringValue;
const char *ipxx = [ip_text cStringUsingEncoding:NSUTF8StringEncoding];
ipcc = ipxx;
[self checkconnection];
}

Related

How to set objective c label with cons char function in c

I want to run my function TestConnection(const char) and set the value from it for my label in objective c. Any help would be greatly apprecitated I keep getting this error "Incompatible integer to pointer conversion sending 'char' to parameter of type 'const char *_Nonull' in xcode.
Here is my c code
fucn.c
const char TestConnection(const char *ip)
{
//char ipAddr[] = "133.131.232.131";
char *val = P(ip);
char *valb = "0packets";
if(strcmp(val, valb) == 0)
{
printf("%s\n", "noconnection");
//return "noconneciton";
}
else
{
printf("%s\n", "connected");
//return "connected";
}
return *val;
}
func.h
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
const char TestConnection(const char *ip);
objective c code Viewcont.m
- (void)checkconneciton:(NSString*)ip {
const char *ipc = [ip UTF8String];
//TestConnection(ipc);
//below is the line with the error.
NSString* xx = [NSString stringWithUTF8String:TestConnection(ipc)];
_ip_label.stringValue = xx;
}
TestConnection is defined as returning a single character, not a string.
It needs to return a string -- const char * -- which can then be used to initialize the NSString.

Why Does This Objective C/C++ Code Require main.m instead of main.mm?

I get strange code errors when I rename the following command line program from main.m to main.mm. Works just fine as main.m. Anyone know why?
https://stackoverflow.com/a/36469891/105539
SOURCE
#import <Foundation/Foundation.h>
void detectNewFile (
ConstFSEventStreamRef streamRef,
void *clientCallBackInfo,
size_t numEvents,
void *eventPaths,
const FSEventStreamEventFlags eventFlags[],
const FSEventStreamEventId eventIds[])
{
int i;
char **paths = eventPaths;
printf("GOT AN EVENT!!!!\n");
for (i=0; i<numEvents; i++) {
printf("Change %llu in %s, flags %u\n", eventIds[i], paths[i], (unsigned int)eventFlags[i]);
}
}
int main(int argc, const char * argv[]) {
#autoreleasepool {
short nPathCount = 2;
CFStringRef mypath[nPathCount];
mypath[0] = CFSTR("/Users/mike/Documents");
mypath[1] = CFSTR("/Users/mike/Downloads");
CFArrayRef pathsToWatch = CFArrayCreate(NULL, (const void **)&mypath, nPathCount, NULL);
void *callbackInfo = NULL;
CFAbsoluteTime latency = 1.0; // seconds
FSEventStreamRef hStream = FSEventStreamCreate(NULL,
&detectNewFile,
callbackInfo,
pathsToWatch,
kFSEventStreamEventIdSinceNow,
latency,
kFSEventStreamCreateFlagFileEvents
);
FSEventStreamScheduleWithRunLoop(hStream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
FSEventStreamStart(hStream);
printf("Waiting on new file creations...\n");
CFRunLoopRun(); // runs in an endless loop, only letting the callback function run
} // end autorelease pool
return 0;
}
ERRORS
FOR:
char **paths = eventPaths;
Cannot initialize a variable of type 'char **' with an lvalue of type 'void *'
FOR:
FSEventStreamRef hStream = FSEventStreamCreate(NULL,
&detectNewFile,
callbackInfo,
pathsToWatch,
kFSEventStreamEventIdSinceNow,
latency,
kFSEventStreamCreateFlagFileEvents
);
No matching function for call to 'FSEventStreamCreate'
Thanks to #johnelemans, I found the problems. In C, it's legal to have automatic casting from void * to char **, but not in C++, which is what the .mm file would switch this into. The fix is to use casting:
char **paths = (char **)eventPaths;
Then, on the FSEventStreamCreate, it didn't like the void * instead of this:
FSEventStreamContext *callbackInfo = NULL;
...and didn't like the CFAbsoluteTime instead of:
CFTimeInterval latency = 1.0; // seconds
Then, you need to add CoreServices.framework library to the build steps.
I made those changes and it compiles now.

Implementing a header in Objective C

I'm completely new to Objective C and I'm trying to use it to wrap a C-library. I have a main.m wrap.m and wrap.h files. From what I gather in the header file I included #interface and in the source file I will include #implementation However I'm not really understanding what to include in each of them. Right now my main file is:
int copy_data(struct archive *ar, struct archive *aw) {
for (;;) {
const void *buff;
size_t size;
off_t offset;
int r = archive_read_data_block(ar, &buff, &size, &offset);
if (r == ARCHIVE_EOF)
return (ARCHIVE_OK);
archive_write_data_block(aw, buff, size, offset);
}
}
int main(int argc, const char * argv[])
{
#autoreleasepool {
struct archive *a;
struct archive *ext;
struct archive_entry *entry;
int flags;
int r;
/* Select which attributes we want to restore. */
flags = ARCHIVE_EXTRACT_TIME;
flags |= ARCHIVE_EXTRACT_PERM;
flags |= ARCHIVE_EXTRACT_ACL;
flags |= ARCHIVE_EXTRACT_FFLAGS;
a = archive_read_new();
archive_read_support_format_all(a);
archive_read_support_compression_all(a);
ext = archive_write_disk_new();
archive_write_disk_set_options(ext, flags);
archive_write_disk_set_standard_lookup(ext);
r = archive_read_open_filename(a, argv[1], 10240);
for (;;) {
r = archive_read_next_header(a, &entry);
if (r == ARCHIVE_EOF)
break;
r = archive_write_header(ext, entry);
if (archive_entry_size(entry) > 0) {
copy_data(a, ext);
}
archive_write_finish_entry(ext);
}
archive_read_close(a);
archive_read_free(a);
archive_write_close(ext);
archive_write_free(ext);
NSLog(#"No Issues");
}
return 0;
}
So far what I'm getting in my wrap.h file is:
typedef struct{
int *a;
int *ext;
}archive;
#interface main : NSObject
#property int flags;
#property int r;
I don't know if that is close to what I need to do, and I'm getting errors on my ARCHIVE_EXTRACT saying they are undeclared identifiers which I assume also have to go into my wrap.h file but I'm not sure how to do that. Any help at all would be appreciated!
If you start your project in Xcode using the CommandLineTool template, you can select your language to be "C" or "C++", so you wouldn't have to mess with Objective-C at all.
As for the .h file that you currently have, don't do "#property" or "#interface" for "main". "main" is a C style function and not an Objective-C thing.
If you are actually interested in an objectivec solution, follow Michael Dautermann's instructions to start a new Command Line project but instead of Type C use the Foundation option. This will give you a working main (just a regular c function). Then select new->objective c class to create your wrap.h/wrap.m. In the wrap.h you will pretty much exclusively be declaring your own objectivec public wrapper methods. In the wrap.m, you'll be importing what you want to wrap, and defining your wrapper functions.
//
// main.m
//
#import <Foundation/Foundation.h>
#import "wrap.h"
int main(int argc, const char * argv[])
{
#autoreleasepool {
[wrap wrappedStuff];
}
return 0;
}
//
// wrap.h
//
----------
#import <Foundation/Foundation.h>
#interface wrap : NSObject
+ (void)wrappedStuff;
#end
//
// wrap.m
//
#import "wrap.h"
#include "WhatImWrapping.h"
#implementation wrap
int copy_data(struct archive *ar, struct archive *aw) {
for (;;) {
const void *buff;
size_t size;
off_t offset;
int r = archive_read_data_block(ar, &buff, &size, &offset);
if (r == ARCHIVE_EOF)
return (ARCHIVE_OK);
archive_write_data_block(aw, buff, size, offset);
}
}
+ (void)wrappedStuff
{
struct archive *a;
struct archive *ext;
struct archive_entry *entry;
int flags;
int r;
/* Select which attributes we want to restore. */
flags = ARCHIVE_EXTRACT_TIME;
flags |= ARCHIVE_EXTRACT_PERM;
flags |= ARCHIVE_EXTRACT_ACL;
flags |= ARCHIVE_EXTRACT_FFLAGS;
a = archive_read_new();
archive_read_support_format_all(a);
archive_read_support_compression_all(a);
ext = archive_write_disk_new();
archive_write_disk_set_options(ext, flags);
archive_write_disk_set_standard_lookup(ext);
r = archive_read_open_filename(a, argv[1], 10240);
for (;;) {
r = archive_read_next_header(a, &entry);
if (r == ARCHIVE_EOF)
break;
r = archive_write_header(ext, entry);
if (archive_entry_size(entry) > 0) {
copy_data(a, ext);
}
archive_write_finish_entry(ext);
}
archive_read_close(a);
archive_read_free(a);
archive_write_close(ext);
archive_write_free(ext);
NSLog(#"No Issues");
}
#end

How to correctly use InitWindow in Objective-C OpenGL?

What am doing wrong ?
I am trying to learn OpenGL and Objective-C, i am porting it code from C to Objective-C.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <GL/glew.h>
#include <GL/freeglut.h>
#define WINDOW_TITLE_PREFIX "Chapter 1"
int CurrentWidth = 800,
CurrentHeight = 600,
WindowHandle = 0;
void Initialize(int, char*[]);
void InitWindow(int, char*[]);
void ResizeFunction(int, int);
void RenderFunction(void);
int main(int argc, char* argv[])
{
Initialize(argc, argv);
glutMainLoop();
exit(EXIT_SUCCESS);
}
void Initialize(int argc, char* argv[])
{
InitWindow(argc, argv);
fprintf(
stdout,
"INFO: OpenGL Version: %s\n",
glGetString(GL_VERSION)
);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
}
void InitWindow(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitContextVersion(4, 0);
glutInitContextFlags(GLUT_FORWARD_COMPATIBLE);
glutInitContextProfile(GLUT_CORE_PROFILE);
glutSetOption(
GLUT_ACTION_ON_WINDOW_CLOSE,
GLUT_ACTION_GLUTMAINLOOP_RETURNS
);
glutInitWindowSize(CurrentWidth, CurrentHeight);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
WindowHandle = glutCreateWindow(WINDOW_TITLE_PREFIX);
if(WindowHandle < 1) {
fprintf(
stderr,
"ERROR: Could not create a new rendering window.\n"
);
exit(EXIT_FAILURE);
}
glutReshapeFunc(ResizeFunction);
glutDisplayFunc(RenderFunction);
}
void ResizeFunction(int Width, int Height)
{
CurrentWidth = Width;
CurrentHeight = Height;
glViewport(0, 0, CurrentWidth, CurrentHeight);
}
void RenderFunction(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glutSwapBuffers();
glutPostRedisplay();
}
I got this code from http://openglbook.com/the-book/chapter-1-getting-started/
I've done this but i am no realy sure what is the error i think the problem is with pointers.
header.h
#import <Foundation/Foundation.h>
#import <stdio.h>
#import <string.h>
#import <GL/glew.h>
#import <GL/freeglut.h>
#define WINDOW_TITLE_PREFIX "test gl objective c"
#interface princ : NSObject {
int CurrentWidth;
int CurrentHeight;
int WindowHandle;
}
-(void)InitValues;
-(void)ResizeFunction;
-(void)RenderFunction;
-(void)InitWindow: (int)argc: (char*[])argv:(void*)FoundRZ:(void*)FoundRD;
-(void)Initialize: (int)argc: (char*[])argv;
#end
#implementation princ
-(void)InitValues {
CurrentWidth = 800;
CurrentHeight = 600;
WindowHandle = 0;
}
-(void)ResizeFunction {
int Width = 0;
int Height = 0;
CurrentWidth = Width;
CurrentHeight = Height;
glViewport(0, 0, CurrentWidth, CurrentHeight);
}
-(void)RenderFunction {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glutSwapBuffers();
glutPostRedisplay();
}
-(void)InitWindow: (int)argc: (char*[])argv:(void*)FoundRZ:(void*)FoundRD {
glutInit(&argc, argv);
glutInitContextVersion(4, 0);
glutInitContextFlags(GLUT_FORWARD_COMPATIBLE);
glutInitContextProfile(GLUT_CORE_PROFILE);
glutSetOption (
GLUT_ACTION_ON_WINDOW_CLOSE,
GLUT_ACTION_GLUTMAINLOOP_RETURNS
);
glutInitWindowSize(CurrentWidth, CurrentHeight);
WindowHandle = glutCreateWindow(WINDOW_TITLE_PREFIX);
if(WindowHandle < 1) {
fprintf(
stderr, "ERROR: Could not create a new rendering window.\n"
);
exit(EXIT_FAILURE);
}
glutReshapeFunc(FoundRZ);
glutDisplayFunc(FoundRD);
}
-(void)Initialize: (int)argc: (char*[])argv {
fprintf(stdout, "INFO: OpenGL Version: %s\n", glGetString(GL_VERSION));
}
#end
1.m
#import "header.h"
int main (int argc, char *argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSLog(#"hello");
princ *GLMAIN = [[princ alloc] init];
[GLMAIN InitValues];
[GLMAIN InitWindow:argc:argv:[GLMAIN ResizeFunction]:[GLMAIN RenderFunction]];
[GLMAIN Initialize:argc:argv];
[pool drain];
return 0;
}
Error :
$ clang -ObjC 1.m -o 1 `gnustep-config --objc-flags` -I/usr/local/lib/gcc42/gcc/x86_64-portbld-freebsd9.0/4.2.5/include -fconstant-string-class=NSConstantString -I/usr/local/GNUstep/System/Library/Headers -L/usr/local/GNUstep/System/Library/Libraries -L/usr/local/lib -lgnustep-base -I/usr/local/include -L/usr/local/lib -lglut -lGL
1.m:12:31: error: sending 'void' to parameter of incompatible type 'void *';
[GLMAIN InitWindow:argc:argv:[GLMAIN ResizeFunction]:[GLMAIN RenderFunction]];
^~~~~~~~~~~~~~~~~~~~~~~
./header.h:18:52: note: passing argument to parameter 'FoundRZ' here
-(void)InitWindow: (int)argc: (char*[])argv:(void*)FoundRZ:(void*)FoundRD;
^
1.m:12:55: error: sending 'void' to parameter of incompatible type 'void *';
[GLMAIN InitWindow:argc:argv:[GLMAIN ResizeFunction]:[GLMAIN RenderFunction]];
^~~~~~~~~~~~~~~~~~~~~~~
./header.h:18:67: note: passing argument to parameter 'FoundRD' here
-(void)InitWindow: (int)argc: (char*[])argv:(void*)FoundRZ:(void*)FoundRD;
^
2 errors generated.
I am not using mac i am using FreeBSD but i have hope any apple developer can help with this little problem.
I think it's your initWindow method. You're passing a method that returns void to an argument that takes a void*. The main problem here is that glut doesn't support Objective-C method calling, and requires C functions instead, so change your resizeFunction and renderFunction to C functions, then pass it and it should work.

Block life cycle in function?

Block variable in objective-c is a reference and I learned from somewhere infer that following code may be transformed by compiler to another form.
Original code:
typedef int (^block_type)();
block_type create_k(int i)
{
block_type block = ^(){
return i;
};
//[block copy];
return block;
}
Generated Code:
typedef void (*generic_invoke_funcptr)(void *, ...);
struct __block_literal {
void *isa;
int flags;
int reserved;
generic_invoke_funcptr invoke;
struct __block_descriptor_tmp *descriptor;
const int captured_i;
};
static const struct __block_descriptor_tmp {
unsigned long reserved;
unsigned long literal_size;
/* no copy/dispose helpers needed */
} __block_descriptor_tmp = {
0UL, sizeof(struct __block_literal)
};
// ^int (void) { return i; }
int __create_k_block_invoke_(struct __block_literal *bp) {
return bp->captured_i;
}
typedef int (*iv_funcptr)(struct __block_literal *);
typedef int (^block_type)();
block_type create_k(int i)
{
//block_type block = ^(){
// return i;
//};
struct __block_literal __b = {
.isa = &_NSConcreteStackBlock,
.flags = BLOCK_HAS_DESCRIPTOR,
.reserved = 0,
.invoke = (generic_invoke_funcptr)__f_block_invoke_,
.descriptor = &__block_descriptor_tmp,
.captured_i = i
};
struct __block_literal *block = &__b;
return block;
}
So |_b| in stack and block is only a reference to |_b|. If |create_k| return |block|, the receiver only get a invalid address.
But
int main(int argc, const char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
printf("%d\n", create_k(40)());
[pool drain];
return 0;
}
By exec it, print |40| and |block| is a valid block. What's the matter?
My guess would be that the memory for that stack frame hasn't been zeroed yet. Try calling another function between create_k() and printf() to get some other random data in there.